I am trying to read simple sensor reading from a arduino. The arduino is connected to COM3 (used for sending data and programming the arduino). The C# Programm is very simple and tries to read what the arduino sends. Problem: I can not open COM3 Port with C# or the arduino when the other side (C# or arduino respectively) already opened it. Just sending without opening doesnt produce any results aswell. How are you supposed to "connect" them? My understanding was that both devices open the port with the same baudrate and then you can send and read data. When I am trying to open, I will get a UnauthorizedAccess on the C# side or a "can't open serial" on the arduino side.
Arduino C-Code:
#include <DHT.h>
#define DHTPIN A4
#define DHTTYPE DHT11
#define THERPIN A0
DHT dht(DHTPIN,DHTTYPE);
String hum="Humidity:";
String temptext="Temp:";
String semi=";";
void setup() {
Serial.begin(9600);
dht.begin();
pinMode(A0,INPUT);
}
void loop() {
float humidity = dht.readHumidity();
delay(300);
float temp = dht.readTemperature();
delay(300);
if (isnan(humidity)||isnan(temp))
{
Serial.println("Fehler beim Lesen(NAN)");
delay (5000);
}else
{
Serial.print(temp + semi);
Serial.print(humidity);
Serial.flush();
delay(1000);
}
}
C# Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO.Ports;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
SerialPort serialPort1;
serialPort1 = new SerialPort();
serialPort1.PortName = "COM3";
serialPort1.BaudRate = 9600;
serialPort1.DtrEnable = true;
REPEAT:
if (serialPort1.IsOpen)
{
string reading = serialPort1.ReadLine();
Console.WriteLine(reading);
serialPort1.Close();
}
else
{
Console.WriteLine("closed,opening");
serialPort1.Open();
goto REPEAT;
}
}
}
}
While searching the solution was always that another programm was already using the COM Port, but isn't that exactly what I need to communicate? Obviously, the arduino has to use the same COM-Port as my C# app, as far as I understand.
Thanks