Writing value seril port and reading it with C#

Hey guys,

My problem is that, I use potentiometer and can get values between 0 - 1023. However, I try to write serial port is that, if potentiometer value < 500 write 1 else write 2.

My arduino codes is below, However on C# it shows me different datas like 49, 13 ,10 etc. However, I try to get only 1 and 2. I code for it serial.write(1) and serial write(2). I will share my c# codes below.

====Arduino codes===

void setup()
{
Serial.begin(9600);
}

void loop()
{
int position = analogRead(A0);
Serial.println(position);

if(position<=500)
{
Serial.write(1);
Serial.flush();
delay(20);
}
else
{
Serial.write(2);
Serial.flush();
delay(20);
}
}

=================C# codes==============

using UnityEngine;
using System.Collections;
using System.IO.Ports;
using System.Text;

public class cubee : MonoBehaviour {

SerialPort sp = new SerialPort(“COM3”,9600);

// Use this for initialization
void Start () {

sp.Open ();
sp.ReadTimeout = 2;

}

// Update is called once per frame
void Update () {

if (sp.IsOpen) {
try
{
int asd = sp.ReadChar();

Debug.Log(asd);
}
catch(System.Exception)
{

}
}
}

}

asd values should be 1 or 2 but ıt’s values always change like 10, 54, 13 49. I do not understand why. Does anybody can help me?

Thank you

It's printing the ASCII values for what you send.

49's the 1, and 10 and 13 are line feeds and carriage returns.

The numbers 49, 13 and 10 are the Ascii codes for 1, Carriage Return and Linefeed.

Your C# program needs to convert those numbers into characters. In Python you do that with chr(49). I don't know C#

...R

Do your testing using the serial monitor first. If you use Serial.print(); (or Serial.println():wink: instead of Serial.write(); you should see the value as a numeric representation of the value.

Yeah, I used serial monitor. But I do not know, if serial.println(1) writes port or not ? By the way In my C# codes I write ReadChar() ısn’t this converting ASCII to char ?

drmmm:
By the way In my C# codes I write ReadChar() ısn't this converting ASCII to char ?

Obviously not if you get 49 rather than 1 - but that is not an Arduino question.

...R