how to send a char from arduino to visual studio

i want to send a char from arduino code to serial port, then visual studio will receive char 'a' and compare with char 'a' which i put in visual studio's code, if result is true, print" found\n" and writeData 'b' to reply arduino's code to ligh led, else writeData'c' to arduino and led off but maybe my code have some problem and visual can't relize char'a' i have sent from arduino so it return true
i need a advice from every body!
code arduino:
int button=6;
#define motor 8
#define gnd 7
#define led 5
char f;
byte k=0;
char g[3]="a\n";
void setup() {
Serial.begin(9600);
pinMode(6,INPUT);
pinMode(motor, OUTPUT);
pinMode(gnd, OUTPUT);
pinMode(led, OUTPUT);
}

void loop() {
Serial.write("a\n");
Serial.flush();
delay(5000);
f=Serial.read();
if(f=='b')
{
digitalWrite(led,LOW);
}
else
{
digitalWrite(led,HIGH);
}
}
code visual studio:
#include <stdio.h>
#include <tchar.h>
#include "SerialClass.h" // Library described above
#include
#include <conio.h>

// application reads from the specified serial port and reports the collected data
int _tmain(int argc, _TCHAR* argv[])
{
printf("Welcome to the serial test app!\n\n");

Serial* SP = new Serial("COM7"); // adjust as needed

if (SP->IsConnected())
printf("We're connected\n");
char incomingData[3] = "";

int dataLength=2;
int readResult = 0;

while(SP->IsConnected())
{

readResult = SP->ReadData(incomingData,dataLength);
// printf("Bytes read: (0 means no data available) %i\n",readResult);
incomingData[readResult] = 0;
printf("%s",incomingData);
Sleep(1000);
if(incomingData=="a")
{
printf("found\n");
SP->WriteData("b",2);
Sleep(1000);

}

else
{
printf("not found\n");
SP->WriteData("c",2);
Sleep(1000);

}
Sleep(500);

}
return 0;
}

advice #1

Please correct your post above and add code tags around your code. [code] // your code here [/code]. it should look like this:// your code here

advice #2
your code is making bets on when things will come back, you have active delays (5 seconds, 1 seconds) that are totally counter productive. read, understand and play with Serial Input Basics from Robin before doing anything else.

advice #3
be ready for the unexpected... is your code robust?
  incomingData[readResult] = 0; what if readResult is larger than 2? (also best practice is to put '\0' instead of 0 so that the code is self documented you are ending the string)

Suggestion for your piece of code:
        if(incomingData=="a") so you are sending "a\n" and you check against "a"? do you think that "a" and "a\n" are the same strings?

how to send a char from arduino to visual studio

You can NOT do that. Visual Studio does NOT read the serial port. You can write an application, using Visual Studio, that CAN read from the serial port.

how to fix visual studio code to it can relize char 'a' from arduino! i try anoher way but it's impossible!
my teacher give me a advice:" you should send only char from arduino to serial port and establish same protocol for arduino and visual studio about send and receive a char" but i think it just involves com number which i have written in my code and in serial.cpp and sericlass.h they established parameters i don't want to fix! So i need a advice from every one!

Have you checked what I told you....

i'm reading example in link which you told me! but it's a arduino code and i still a visual studio code which can relize a char i send from arduino! maybe i will think more about code after i finish reading example on your link

Please stop using the "report to moderator" control

have you read that part of my post?

Suggestion for your piece of code:
        if(incomingData=="a") so you are sending "a\n" and you check against "a"? do you think that "a" and "a\n" are the same strings?

i have fix code in visual studio and arduino but it still has a error, i don't know why?

Here is arduino code:

#define sensor 9
#define motor 8
#define gnd 7
const byte numchars=32;
boolean newData=false;
boolean insend=true;
char receivedchars[numchars];
void setup() {
Serial.begin(9600);
pinMode(sensor,INPUT);
pinMode(motor, OUTPUT);
pinMode(gnd, OUTPUT);
}
void recvWithMarkers()
{
static boolean recvinprogress=false;
static byte ndx=0;
char startmarker='<';
char endmarker='>';
char rc;
while(Serial.available()>0 && newData==false)
{
rc=Serial.read();
if(recvinprogress==true)
{
if(rc!=endmarker)
{
receivedchars[ndx]=rc;
ndx++;
if(ndx>numchars)
{
ndx=numchars-1;
}
}
else
{
receivedchars[ndx]='\0';
recvinprogress=false;
ndx=0;
newData=true;
}
}
else if(rc==startmarker)
{
recvinprogress=true;
}
}
}
void showNewData()
{
if(newData==true)
{
Serial.println("this just in...");
Serial.println(receivedchars);
newData=false;
}
}
void loop() {
if(digitalRead(sensor)==0 && insend==true)
{
Serial.write("");
Serial.flush();
insend=false;
}
recvWithMarkers();
if(receivedchars=="")
{
showNewData();
insend=true;
digitalWrite(motor,1);
digitalWrite(gnd,0);
}
else if(receivedchars=="")
{
showNewData();
digitalWrite(motor,0);
digitalWrite(gnd,0);
}
}

And Here is visual studio code:

#include <stdio.h>
#include <tchar.h>
#include "SerialClass.h"
#include
#include <conio.h>
const int numchars=32;
char receivedchars[numchars];
bool newData=false;
int readResult = 0;
char incomingData[32] = "";
int dataLength=31;
void recvWithMarkers()
{
static bool recvinprogress=false;
static int ndx=0;
char startmarker='<';
char endmarker='>';
while(readResult>0 && newData==false)
{
for(int i=0;i<=readResult;i++)
{
if(incomingData*==startmarker)*

  • {*
  • recvinprogress=true;*
  • }*
  • if (recvinprogress==true)*
  • {*
    _ if(incomingData*!=endmarker)_
    _
    {_
    _ receivedchars[ndx]=incomingData;
    ndx=ndx+1;
    if(ndx>=numchars)
    {
    ndx=numchars-1;
    }
    }
    else{
    receivedchars[ndx]='\0';
    recvinprogress==false;
    ndx=0;
    newData=true;
    }
    }
    }
    }
    }
    void showNewData()
    {
    if(newData==true)
    {
    printf("this just in...");
    printf("%s",receivedchars);
    newData=false;
    }
    }_
    int _tmain(int argc, _TCHAR argv[])

    {
    * printf("Welcome to the serial test app!\n\n");*
    _ Serial* SP = new Serial("COM7");
    * if (SP->IsConnected())
    printf("We're connected\n");*_

* while(SP->IsConnected())*
* {*

* readResult = SP->ReadData(incomingData,dataLength);*
* incomingData[readResult] = 0;*
* recvWithMarkers();*
* if(receivedchars=="
")*
* {*
* showNewData();*
* SP->WriteData("",32);*
* Sleep(1000);*
* }*
* else*
* {*
* showNewData();*
* SP->WriteData("",32);*
* Sleep(1000);*
* }*

* }*
* return 0;*
}

i want to send a char like'' from arduino when sensor detect a thing to visual studio through serial port and after visual studio receive a char if that char is same char return value is true, visual studio print that char and send another char like'' reply arduino and not visual studio also print char but it send another char like '' to rely arduino!
here is arduino code

#define sensor 9
#define motor 8
#define gnd 7
const byte numchars=32;
boolean newData=false;
boolean insend=true;
char receivedchars[numchars];
void setup() {
 Serial.begin(9600);
 pinMode(sensor,INPUT);
 pinMode(motor, OUTPUT);
 pinMode(gnd, OUTPUT);
}
void recvWithMarkers()
{
 static boolean recvinprogress=false;
 static byte ndx=0;
 char startmarker='<';
 char endmarker='>';
 char rc;
 while(Serial.available()>0 && newData==false)
 {
   rc=Serial.read();
   if(recvinprogress==true)
   {
   if(rc!=endmarker)
   {
     receivedchars[ndx]=rc;
     ndx++;
     if(ndx>numchars)
     {
       ndx=numchars-1;
     }
   }
   else
   {
     receivedchars[ndx]='\0';
     recvinprogress=false;
     ndx=0;
     newData=true;
   }
   }
   else if(rc==startmarker)
   {
     recvinprogress=true;
   }
 }
}
void showNewData()
{
 if(newData==true)
 {
   Serial.println("this just in...");
   Serial.println(receivedchars);
   newData=false;
 }
}
void loop() { 
 if(digitalRead(sensor)==0 && insend==true)
 { 
Serial.write("<a>");
Serial.flush();
insend=false;
 }
recvWithMarkers();
 if(receivedchars=="<b>")
 {
   showNewData();
   insend=true;
   digitalWrite(motor,1);
   digitalWrite(gnd,0);
 }
 else if(receivedchars=="<c>")
 {
   showNewData();
   digitalWrite(motor,0);
   digitalWrite(gnd,0);
 }
}

And here is visual studio code

#include <stdio.h>
#include <tchar.h>
#include "SerialClass.h"   
#include <string>
#include <conio.h>
const int numchars=32;
char receivedchars[numchars];
bool newData=false;
int readResult = 0;
char incomingData[32] = "";
int dataLength=31;
void recvWithMarkers()
{
static bool recvinprogress=false;
static int ndx=0;
char startmarker='<';
char endmarker='>';
while(readResult>0 && newData==false)
{
for(int i=0;i<=readResult;i++)
{
if(incomingData[i]==startmarker)
{
recvinprogress=true;
}
if (recvinprogress==true)
{
if(incomingData[i]!=endmarker)
{
receivedchars[ndx]=incomingData[i];
ndx=ndx+1;
if(ndx>=numchars)
{
ndx=numchars-1;
}
}
else{
receivedchars[ndx]='\0';
recvinprogress==false;
ndx=0;
newData=true;
}
}
}
}
}
void showNewData()
{
if(newData==true)
{
printf("this just in...");
printf("%s",receivedchars);
newData=false;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
  printf("Welcome to the serial test app!\n\n");

  Serial* SP = new Serial("COM7");   

  if (SP->IsConnected())
  printf("We're connected\n");
  
  
  
  while(SP->IsConnected())
  {
     
     readResult = SP->ReadData(incomingData,dataLength);
     incomingData[readResult] = 0;
     recvWithMarkers();

        if(receivedchars=="<a>")
        {
        showNewData();
        SP->WriteData("<b>",32);
        Sleep(1000);
}
        else
        {
        showNewData();
        SP->WriteData("<c>",32);
        Sleep(1000);
}
        
        
  }
  return 0;
}

And i want to send a imag about error

Untitled.png

to visual studio

That will be completely useless. Visual Studio can NOT connect to the serial port.

You COULD create an application using Visual Studio that could connect to the serial port.

The app that you did write using Visual Studio has some fundamental flaws that YOU could have detected by judiciously printing stuff.

What, EXACTLY, did the application read from the serial port? What, EXACTLY, did recvWithMarkers() do with that data?

If you send , receivedchars will NOT contain "". It WILL contain "abc".

So, comparing receivedchars with "" will never result in a match.

On the Arduino side. recvWithMarkers() also strips off the < and >, so comparing the array contents with "" is wrong, too.

The comparison statement that you have actually compares the address of the receivedchars array with the address of the string literal, which will never be true.

strcmp() bears looking into.

  if(receivedchars=="<b>")

THAT is STILL nonsense.

         if(receivedchars=="<a>")

So is this.

You haven't read ANYTHING that I have posted. I'm done trying to help you.

thank PaulIS but i still have no idea about fixing this problem? i have read a topic about serial input basics of robin2, robin write a way to rely a char by using start"<" and ">" endmarker, so i think i can use this way for arduino and visual studio! but i doesn't work so if you have any idea, please write a simple code or something's useful for me! thanks u

but i doesn't work so if you have any idea, please write a simple code or something's useful for me! thanks u

Nonsense. It works perfectly.

Print what you store in incomingData in main().

Print what you store in receivedchars in recvWithMarkers().

Then, tell me how you expect receivedchars to equal "".

no, i mean code no error for arduino and visual studio but when i put a thing to sensor, char'<a' is written to serial port, i can see it through monitor scene in arduino but when i run code visual it appear a error which i post in imagine i add with code and status, you see it, don't you?

here is image about error and thing appear in monitor scene of visual studio, PaulIS you can understand them

Anonymous printing sucks.

Print some identifier before what you are printing, and some end-of-string indicator after it.

   Console.WriteLine("incomingData: [{0}]", incomingData);
   Console.WriteLine("receivedchars: [{0}]", receivedchars);

today, my teacher write a examples code in arduino, he send only char 'a' in void setup and when i compare incoming data in visual studio with it, it write 'found\n' but just 'found' appear 2 times and after that it print' not found' again, when print 'found' char'a' in incomingdata doesns't appear although i write code print it before compare char with 'a' by strcmp in if, when print 'not found', incomingdata appear again before print 'not found', i don't know why? PaulIS, you can know it, can't you?

You changed your code. You did not post it. There is not a hope in hell that anyone can help you without seeing your code.

sorry PaulIs, now visual can recevive and know my char which i send from arduino, but i have some trouble with write data to rely arduino, can you help me again?
here is visual studio code:

#include <stdio.h>
#include <tchar.h>
#include "SerialClass.h"   
#include <string>
#include <conio.h>

int readResult = 0;
char incomingData[3] = "";
int dataLength=3;

int _tmain(int argc, _TCHAR* argv[])
{
   printf("Welcome to the serial test app!\n\n");

   Serial* SP = new Serial("COM7");   

   if (SP->IsConnected())
   printf("We're connected\n");
   
   
   
   while(SP->IsConnected())
   {
      
      readResult = SP->ReadData(incomingData,dataLength);
      incomingData[readResult] = 0;
	  printf("%s\n",incomingData);
	  
         if(!strcmp(incomingData,"<a>"))
         {
        printf("found a\n");
		SP->WriteData("<b>",3);
         Sleep(1000);
		 }
         else
         {
         printf("not found a\n");
		 SP->WriteData("<c>",3);
         Sleep(1000);
		 }
   }
   return 0;
}

and here is serial.cpp code:

include "stdafx.h"
#include "SerialClass.h"

Serial::Serial(char *portName)
{
    //We're not yet connected
    this->connected = false;

    //Try to connect to the given port throuh CreateFile
    this->hSerial = CreateFile(portName,
            GENERIC_READ | GENERIC_WRITE,
            0,
            NULL,
            OPEN_EXISTING,
            FILE_ATTRIBUTE_NORMAL,
            NULL);

    //Check if the connection was successfull
    if(this->hSerial==INVALID_HANDLE_VALUE)
    {
        //If not success full display an Error
        if(GetLastError()==ERROR_FILE_NOT_FOUND){

            //Print Error if neccessary
            printf("ERROR: Handle was not attached. Reason: %s not available.\n", portName);

        }
        else
        {
            printf("ERROR!!!");
        }
    }
    else
    {
        //If connected we try to set the comm parameters
        DCB dcbSerialParams = {0};

        //Try to get the current
        if (!GetCommState(this->hSerial, &dcbSerialParams))
        {
            //If impossible, show an error
            printf("failed to get current serial parameters!");
        }
        else
        {
            //Define serial connection parameters for the arduino board
            dcbSerialParams.BaudRate=CBR_9600;
            dcbSerialParams.ByteSize=8;
            dcbSerialParams.StopBits=ONESTOPBIT;
            dcbSerialParams.Parity=NOPARITY;

             //Set the parameters and check for their proper application
             if(!SetCommState(hSerial, &dcbSerialParams))
             {
                printf("ALERT: Could not set Serial Port parameters");
             }
             else
             {
                 //If everything went fine we're connected
                 this->connected = true;
                 //We wait 2s as the arduino board will be reseting
                 Sleep(ARDUINO_WAIT_TIME);
             }
        }
    }

}

Serial::~Serial()
{
    //Check if we are connected before trying to disconnect
    if(this->connected)
    {
        //We're no longer connected
        this->connected = false;
        //Close the serial handler
        CloseHandle(this->hSerial);
    }
}

int Serial::ReadData(char *buffer, unsigned int nbChar)
{
    //Number of bytes we'll have read
    DWORD bytesRead;
    //Number of bytes we'll really ask to read
    unsigned int toRead;

    //Use the ClearCommError function to get status info on the Serial port
    ClearCommError(this->hSerial, &this->errors, &this->status);

    //Check if there is something to read
    if(this->status.cbInQue>0)
    {
        //If there is we check if there is enough data to read the required number
        //of characters, if not we'll read only the available characters to prevent
        //locking of the application.
        if(this->status.cbInQue>nbChar)
        {
            toRead = nbChar;
        }
        else
        {
            toRead = this->status.cbInQue;
        }

        //Try to read the require number of chars, and return the number of read bytes on success
        if(ReadFile(this->hSerial, buffer, toRead, &bytesRead, NULL) && bytesRead != 0)
        {
            return bytesRead;
        }

    }

    //If nothing has been read, or that an error was detected return -1
    return -1;

}


bool Serial::WriteData(char *buffer, unsigned int nbChar)
{
    DWORD bytesSend;

    //Try to write the buffer on the Serial port
    if(!WriteFile(this->hSerial, (void *)buffer, nbChar, &bytesSend, 0))
    {
        //In case it don't work get comm error and return false
        ClearCommError(this->hSerial, &this->errors, &this->status);

        return false;
    }
    else
        return true;
}

bool Serial::IsConnected()
{
    //Simply return the connection status
    return this->connected;
}