Arduino Serial commutation using visual studio c++ - visual-c++

I've been working on the school project with Gird-Eye.
I use the Arduino Uno to access the data form Grid-Eye.
And now I want to implement a serial communication test program with c++.
I use the library form here:
http://playground.arduino.cc/Interfacing/CPPWindows
Here is Arduino Code:
int data[64];
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
for (int i = 0; i < 64; ++i) {
data[i] = i;
}
}
void loop() {
// put your main code here, to run repeatedly:
if (Serial.available() > 0) {
char c = Serial.read();
if (c == 'h') { Serial.write("Hello\r\n"); }
else if (c == 'i') {
for (int i = 0; i < 64; ++i)
Serial.println(data[i]);
}
}
}
And Here is main.cpp code:
int main() {
Serial* port = new Serial("COM5");
if (port->IsConnected()) cout << "Connection established!!!" << endl;
char data[256] = "";
int datalength = 256;
int readResult = 0;
for (int i = 0; i < 256; ++i) { data[i] = 0; }
string str;
char command[] = "i";
int msglen = strlen(command);
port->WriteData(command, msglen);
while (1) {
while (port->ReadData(data, 256) != -1) {
printf("%s", data);
}
}
system("pause");
return 0;
}
I can get the value successfully with this interface.
However the window additional shows extra value.
For Example, the program should ends like this.
....
61
62
63
But I get
...
61
62
63
50
51
52
53
I have no idea why there is extra value.
Could anyone tell me why?
Thanks!!!

I believe that you need to terminate the string that you put into the data buffer in each loop iteration:
while ((n = port->ReadData(data, 256)) != -1) {
data[n] = 0;
printf("%s", data);
}

Related

Heap buffer overflow error, Leetcode problem 941, Valid Mountain Array, using C

I am currently learning c and trying to do some problems on leetcode to better myself.
The problem: https://leetcode.com/problems/valid-mountain-array/
I am getting an error as such, error message apperently a read error.
However whenever i run my code on my pc i don't get any errors, even using valgrind.
Here is my code:
bool validMountainArray(int* arr, int arrSize)
{
bool is_m_array = false;
bool peek = false;
int peek_point = 0;
int end_of_slope = 0;
int k = 0;
if( arrSize >= 3)
{
while (arr[k] < arr[k+1] && arr[k] < arrSize)
{
k++;
}
peek = true;
peek_point = k;
}
if (peek == true)
{
while(arr[peek_point] > arr[peek_point+1] && arr[peek_point] < arrSize)
{
peek_point++;
end_of_slope = peek_point+1;
printf("end Of SLOPE %d, arrSize %d \n", end_of_slope, arrSize);
}
}
if (peek == true && end_of_slope == arrSize)
{
is_m_array = true;
}
return is_m_array;
}
I have tried several different inputs and they all seem to work just fine!
For example:
int main(int argc, char const *argv[])
{ int arr[9]= {1,2,3,4,5,4,3,2,1};
if (validMountainArray(arr, 9) == true)
{
printf("True");
}
else
{
printf("False");
}
return 0;
}
Will return True.
Anyone got any ide what i am missing here?

CS50 Plurality Problem, error: use of undeclared identifier 'i'

Trying to solve the pset3 plurality problem for the CS50 class, line 93 of my code has been the issue, I'm having some trouble solving the last part of the problem set, printing the winner.
I think the vote totals section is okay, but I can't get the code right for the winners section. When I run the code I receive the following error message:
error: use of undeclared identifier 'i' printf("%s\n", candidates[i].name);
#include <cs50.h>
#include <stdio.h>
#include <string.h>
// Max number of candidates
#define MAX 9
// Candidates have name and vote count
typedef struct
{
string name;
int votes;
}
candidate;
// Array of candidates
candidate candidates[MAX];
// Number of candidates
int candidate_count;
// Function prototypes
bool vote(string name);
void print_winner(void);
int main(int argc, string argv[])
{
// Check for invalid usage
if (argc < 2)
{
printf("Usage: plurality [candidate ...]\n");
return 1;
}
// Populate array of candidates
candidate_count = argc - 1;
if (candidate_count > MAX)
{
printf("Maximum number of candidates is %i\n", MAX);
return 2;
}
for (int i = 0; i < candidate_count; i++)
{
candidates[i].name = argv[i + 1];
candidates[i].votes = 0;
}
int voter_count = get_int("Number of voters: ");
// Loop over all voters
for (int i = 0; i < voter_count; i++)
{
string name = get_string("Vote: ");
// Check for invalid vote
if (!vote(name))
{
printf("Invalid vote.\n");
}
}
// Display winner of election
print_winner();
}
// Update vote totals given a new vote
bool vote(string name)
{
for (int i = 0; i < candidate_count; i++)
{
if (strcmp(name, candidates[i].name) == 0)
candidates[i].votes++;
}
return true;
return false;
}
// Print the winner (or winners) of the election
void print_winner(void)
{
int maxvote = 0;
for (int i = 0; i < candidate_count; i++)
{
if (candidates[i].votes > maxvote)
maxvote = candidates[i].votes;
}
printf("%s\n", candidates[i].name);
return;
}
The i variable is defined only within the context of your loop. When the loop is over, where your print statement tries to print candidates[i].name but i is not defined anymore. Just like how you save your max number of votes, you also need to save your candidate index in a value declared outside of your loop.
int maxvote = 0;
int winnerIndex;
for (int i = 0; i < candidate_count; i++)
{
if (candidates[i].votes > maxvote) {
maxvote = candidates[i].votes;
winnerIndex = i;
}
}
printf("%s\n", candidates[winnerIndex].name);

how to parallel or multithreading 2 function in C++?

I'm a beginner at parallel programming. I have 2 function in my code that I want run this 2 function in parallel (multiThread). can you help me?
func 1:
void Navigation::test_end(Graph::Node *node, dtPolyRef endRef, const float *endPos, int endIdPos)
{
int k=0;
//std::ofstream fout("v4.txt", std::ios_base::app | std::ios_base::out);
auto it2 = myMap2.equal_range(endRef);
for (auto it = it2.first; it != it2.second; ++it) {
int m_npolys = 0;
int n=0;
dtPolyRef m_polys[MAX_POLYS];
int j = it->second.size();
for(int i=0;i<j-1;i++){
if(it->second[i]>0){
m_polys[m_npolys++] =it->second[i];
// fout <<it->second[i]<<" ";
}
currentGraph.AddIntraEdge(node->idNode,endIdPos, node->edges[k].idPos, it->second[j-1], m_polys ,m_npolys); //n=m_npolys
k++;
}
}
==========
func 2:
void Navigation::test_start(Graph::Node *node, dtPolyRef startRef, const float *startPos, int startIdPos)
{
int k=0;
//std::ofstream fout("v4.txt", std::ios_base::app | std::ios_base::out);
auto it2 = myMap2.equal_range(startRef);
for (auto it = it2.first; it != it2.second; ++it) {
int m_npolys = 0;
int n=0;
dtPolyRef m_polys[MAX_POLYS];
int j = it->second.size();
for(int i=0;i<j-1;i++){
if(it->second[i]>0){
m_polys[m_npolys++] =it->second[i];
// fout <<it->second[i]<<" ";
}
currentGraph.AddIntraEdge(node->idNode,startIdPos, node->edges[k].idPos, it->second[j-1], m_polys ,m_npolys); //n=m_npolys
k++;
}
}
now i want to run this 2 function in parallel mode in the main function :
test_start(sNode,startRef,startPos,startIdPos);
test_end(eNode,endRef,endPos, endIdPos);

Visual C++ Critical Section and conditional variables

I have threads and each one will print a string. The code compiles but when i run it it crashes, does not even print one char. Is there any organization mistake in my code? Any idea? Thanks. I checked a few websites but no sense. I am using VS C++ 2013
void threadWork (void) const {
for (unsigned i = 0; i < 4; ++i) {
this_thread::sleep_for(chrono::milliseconds(_sleep_time(_dre)));
EnterCriticalSection(&criticalSection);
if ( boolVar = false)
{
InitializeConditionVariable(&conditionVariable);
InitializeCriticalSection(&criticalSection);
boolVar = true;
}
inUse = true;
while (inUse == true)
{
SleepConditionVariableCS(&conditionVariable, &criticalSection, INFINITE);
for (auto c : _printMe) {
this_thread::sleep_for(chrono::milliseconds(_sleep_time(_dre)));
cout << c;
cout.flush();
}
inUse = false;
LeaveCriticalSection(&criticalSection);
WakeAllConditionVariable(&conditionVariable);
}
}
};

C, convert hex number to decimal number without functions

i'm trying to convert hexadecimal number to decimal number. What i've come up so far is:
#include <unistd.h>
#include <stdio.h>
long convert(char *input, short int *status){
int length = 0;
while(input[length])
{
length++;
}
if(length = 0)
{
*status = 0;
return 0;
}
else
{
int index;
int converter;
int result = 0;
int lastNumber = length-1;
int currentNumber;
for(index = 0; index < length; index++){
if(index == 0)
{
converter = 1;
}
else if(index == 1)
{
converter = 16;
}
else{
converter *= 16;
}
if(input[lastNumber] < 45 || input[lastNumber] > 57)
{
*status = 0;
return 0;
}
else if(input[lastNumber] > 45 && input[lastNumber] < 48)
{
*status = 0;
return 0;
}
else{
if(input[lastNumber] == 45)
{
*status = -1;
return result *= -1;
}
currentNumber = input[lastNumber] - 48;
result += currentNumber * converter;
lastNumber--;
}
}
*status = -1;
return result;
}
}
int main(int argc, char **argv)
{
char *input=0;
short int status=0;
long rezult=0;
if(argc!=2)
{
status=0;
}
else
{
input=argv[1];
rezult=convert(input,&status);
}
printf("result: %ld\n", rezult);
printf("status: %d\n", status);
return 0;
}
Somehow i always get resoult 0. Ia am also not allowed to use any other outher functions (except printf). What could be wrong with my code above?
This:
if(dolzina = 0)
{
*status = 0;
return 0;
}
is not merely testing dolzina, it's first setting it to 0. This causes the else clause to run, but with dolzina equal to 0 which is not the expected outcome.
You should just use == to compare, of course.

Resources