C# console application talking to Arduino via Bluetooth - c#

Not a whole lot to say here other than this doesn't work, and I have no idea why.
The serial output on the Arduino is nothing. The output on the C# code goes down to waiting for a response and then nothing.
The Bluetooth card LED on the Arduino goes green when I start the C# program so there is a connection being made. Just nothing else.
Arduino Code
#include <SoftwareSerial.h> //Software Serial Port
#define RxD 8 // This is the pin that the Bluetooth (BT_TX) will transmit to the Arduino (RxD)
#define TxD 7 // This is the pin that the Bluetooth (BT_RX) will receive from the Arduino (TxD)
SoftwareSerial blueToothSerial(RxD,TxD);
boolean light = false;
void setup(){
Serial.begin(9600); // Allow Serial communication via USB cable to computer (if required)
pinMode(RxD, INPUT); // Setup the Arduino to receive INPUT from the bluetooth shield on Digital Pin 6
pinMode(TxD, OUTPUT); // Setup the Arduino to send data (OUTPUT) to the bluetooth shield on Digital Pin 7
pinMode(13,OUTPUT); // Use onboard LED if required.
}
void loop(){
delay(1000);
if(light){
light = false;
digitalWrite(13,LOW);
}
else{
light = true;
digitalWrite(13,HIGH);
}
//Serial.println(blueToothSerial.available());
blueToothSerial.write("Im alive");
if(blueToothSerial.read()>0){
Serial.write(blueToothSerial.read());
}
}
Core C# Code
static void Main(string[] args)
{
byte[] Command = Encoding.ASCII.GetBytes("It works");//{0x00,0x01,0x88};
SerialPort BlueToothConnection = new SerialPort();
BlueToothConnection.BaudRate = (9600);
BlueToothConnection.PortName = "COM4";
BlueToothConnection.Open();
if (BlueToothConnection.IsOpen)
{
BlueToothConnection.ErrorReceived += new SerialErrorReceivedEventHandler(BlueToothConnection_ErrorReceived);
// Declare a 2 bytes vector to store the message length header
Byte[] MessageLength = { 0x00, 0x00 };
//set the LSB to the length of the message
MessageLength[0] = (byte)Command.Length;
//send the 2 bytes header
BlueToothConnection.Write(MessageLength, 0, MessageLength.Length);
// send the message itself
System.Threading.Thread.Sleep(2000);
BlueToothConnection.Write(Command, 0, Command.Length);
Messages(5, ""); //This is the last thing that prints before it just waits for response.
int length = BlueToothConnection.ReadByte();
Messages(6, "");
// retrieve the reply data
for (int i = 0; i < length; i++)
{
Messages(7, (BlueToothConnection.ReadByte().ToString()));
}
}
}

Okay so there were a few issues that are hard to see from above so I will attempt to explain.
First, RX and TX on the bluetooth card DO NOT go to their equals on the arduino. They go to their opposites.
Example:
Bluetooth Card RX -> TX on Arduino
Bluetooth Card TX -> RX on Arduino
So if you look in the photo of the Arduino above it should be painfully obvious that pins 7 and 8 are the incorrect placement.
The next issue that I was having was poor connectivity.
The power and ground seem to be fine in the above configuration. However, the RX and TX connections need to be soldered in. Otherwise you get a poor connection.
Once I made this changes the above code worked flawlessly.
Hope this helps anyone else having these issues!!

Here is similar code simplified for testing the PC <-> Arduino BT communication. In the code below, the PC sends text to the Arduino, which then echoes it back to the PC. PC writes the incoming text to console.
Set your BT serial port (COM5 in the example) from Windows.
Tested with Arduino Uno, an USB-Bluetooth dongle and the bluetooth module HC-05. Arduino's PIN1(TX) voltage was divided from 5V to 2.5V before feeding it to the module's RX pin).
That's it. Easy!
Arduino:
void setup() {
Serial.begin(9600);
delay(50);
}
void loop() {
if (Serial.available())
Serial.write(Serial.read()); // echo everything
}
C#:
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
public class SerialTest
{
public static void Main()
{
SerialPort serialPort = new SerialPort();
serialPort.BaudRate = 9600;
serialPort.PortName = "COM5"; // Set in Windows
serialPort.Open();
int counter = 0;
while (serialPort.IsOpen)
{
// WRITE THE INCOMING BUFFER TO CONSOLE
while (serialPort.BytesToRead > 0)
{
Console.Write(Convert.ToChar(serialPort.ReadChar()));
}
// SEND
serialPort.WriteLine("PC counter: " + (counter++));
Thread.Sleep(500);
}
}
}

Related

Problem with sending data from c# to arduino for SIM800L

I think I missed something in my code.
Below is my code in C#
public Form1()
{
InitializeComponent();
serialPort1.PortName = "COM2";
serialPort1.BaudRate = 9600;
serialPort1.Parity = Parity.None;
serialPort1.DataBits = 8;
serialPort1.StopBits = StopBits.One;
serialPort1.Handshake = Handshake.RequestToSend;
serialPort1.DtrEnable = true;
serialPort1.RtsEnable = true;
serialPort1.NewLine = System.Environment.NewLine;
}
private void btnSend_Click(object sender, EventArgs e)
{
serialPort1.Open();
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{
string num = "+639952006630\n";
serialPort1.Write(num);
string message = "Your child arrived at our school at " + DateTime.Now + ".";
serialPort1.Write(message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Below is my code in Arduino for sending data using GSM module SIM800L
#include <SoftwareSerial.h>
//SIM800 TX is connected to Arduino D8
#define SIM800_TX_PIN 8
//SIM800 RX is connected to Arduino D7
#define SIM800_RX_PIN 7
//Create software serial object to communicate with SIM800
SoftwareSerial serialSIM800(SIM800_TX_PIN,SIM800_RX_PIN);
void setup() {
//Begin serial comunication with Arduino and Arduino IDE (Serial Monitor)
Serial.begin(9600);
while(!Serial);
//Being serial communication with Arduino and SIM800
serialSIM800.begin(9600);
delay(1000);
//Set SMS format to ASCII
serialSIM800.write("AT+CMGF=1\r\n");
delay(1000);
//getting the number
char remoteNum[20]; // telephone number to send sms
readSerial(remoteNum);
//Send new SMS command and message number
serialSIM800.print("AT+CMGS=\"");
serialSIM800.print(remoteNum);
serialSIM800.print("\"\r\n");
delay(1000);
// getting sms text
char txtMsg[200];
readSerial(txtMsg);
//Send SMS content
serialSIM800.print(txtMsg);
delay(1000);
//Send Ctrl+Z / ESC to denote SMS message is complete
serialSIM800.write((char)26);
delay(1000);
Serial.println("SMS Sent!");
}
/*
Read input serial
*/
char readSerial(char result[]) {
int i = 0;
while (1) {
while (Serial.available() > 0) {
char inChar = Serial.read();
if (inChar == '\n') {
result[i] = '\0';
Serial.flush();
return 0;
}
if (inChar != '\r') {
result[i] = inChar;
i++;
}
}
}
}
void loop() {
}
My confusion/question here is
Whenever I test it using Serial Monitor in Arduino, the code in Arduino sends message to the cellular number successful. But when I use a form in Visual Studio using C#, nothing happens. There are also no errors that appear. I tried F11 also to know if I am missing an error, still I see nothing. But the application does not send SMS to the number.
Help from you guys is very much appreciated. Thank you in advance.
The solution is as obvious as simple. You have all your routines in the Arduino setup which runs only once. So sending one sms from Arduino directly works exactly 1 time.
When connecting via c code, the Arduino is already booted and in the EMPTY loop. So the chance to hit the one time run code is zero.
Put your routines especially
readSerial(remoteNum);
in the loop and it should work as expected.
The first thing you should do before sending the commands with your Visual Studio is that the serialport is correctly configured, you simply have the serial port closed loop, everything you send should receive, If you do not receive anything you have a serial port configuration problem

sniff serial port - .net

I have this Arduino code just for testing purpose:
int num=0;
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println(num);
num+=1;
delay(800);
}
Now it prints an integer and increments its value by one. When I open up Serial Monitor it prints as expected every 800ms.
My Arduino is connected on PORT-6
Now if I try to access the port, it says it is in use, I'm trying to access that from a .NET application. How can I do so?
c# code, collected from the internet, modified a little:
using System;
using System.IO.Ports;
using System.Threading;
namespace ConsoleApp1
{
class Program
{
static SerialPort _serialPort;
public static void Main()
{
_serialPort = new SerialPort();
_serialPort.PortName = "COM6";//Set your board COM
_serialPort.BaudRate = 9600;
_serialPort.Open();
while (true)
{
string a = _serialPort.ReadExisting();
Console.WriteLine(a);
}
}
}
}
How can I sniff data from that serial port ? [Educational Purpose]
You can't open a serial port twice.
If what you want is to get to see what is going through the bus (sniffing), you can use virtual ports and port forwarding, see here for a complete example.
Nothing will stop you from replacing any of the tools discussed in the link with your own code (.NET or other), in case they don't suit your needs or if you have enough determination to reinvent the wheel.

Reading Info sent by arduino to Serial Port with C#

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
Your code is opening and closing the serial port perpetually. This does not work, because when .NET code closes the connection Windows internally will close the port asynchronously. It can take a few seconds before the port is actually closed. This is why the program almost immediately blocks.
Open the connection only once at the start of your program.
Besides: avoid GOTO statements at any cost. Edgar Dijkstra wrote a paper against its use many years ago: Go To Statement Considered Harmful.

How to use the serial port to send information from kinect to arduino?

I have fiddled around with the Kinect SDK and arduino, and I have looked around the web to find a way to pass information from the Kinect to the arduino. I'm only trying to pass some very simple information (i.e. if the kinect recognizes a hand gesture, the arduino do this) and I have found people talking about using the serial port to do this. I looked at the documentations and people's code, but I'm very new to C# and don't really understand how the serial port works. I have the Kinect for Windows v1 and am trying to pass information to a botboarduino. If someone can explain how to set up the serial ports that would be greatly appreciated!
PS. I have been working in Visual Studio 2015 community for the Kinect and in the Arduino IDE for the arduino.
A bit obvious, I know, but start by using SerialPort component from System.IO.Ports namespace.
The examples section of this: https://msdn.microsoft.com/en-us/library/system.io.ports.serialport(v=vs.110).aspx MSDN page offers all the functions you require to get the serial port up, and parse in data. You'll of course need your Serial port open, set to the correct parity on the Arduino end to receive the desired data you want to send and process it - but there are more than enough examples of that.
The examples provided by Mike should give a general layout, but as for setting up the serial port in your program you are most likely going to abide by 9600 8N1.
Here is an example of the initial serial port settings for 9600 8N1 (These are for C++ using Boost libraries, but it should make it clear what you will need to set):
port.set_option(asio::serial_port_base::baud_rate(9600));
port.set_option(asio::serial_port_base::character_size(8));
port.set_option(asio::serial_port_base::flow_control(asio::serial_port_base::flow_control::none));
port.set_option(asio::serial_port_base::parity(asio::serial_port_base::parity::none));
port.set_option(asio::serial_port_base::stop_bits(asio::serial_port_base::stop_bits::one));
When I set this up in the past the only thing I had to ensure was the baud rate on the Arduino matched that of the above settings, otherwise the rest seemed to be default settings. I can't guarantee this in your case though.
You need to write to serial the Arduino is connected to. Windows regards a serial as a file, so to write to the serial, use this class (I use VS2013, but it should work for VS2015 as well):
Header (named SerialClass.h):
#ifndef SERIALCLASS_H_INCLUDED
#define SERIALCLASS_H_INCLUDED
#define ARDUINO_WAIT_TIME 2000
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
class Serial
{
private:
//Serial comm handler
HANDLE hSerial;
//Connection status
bool connected;
//Get various information about the connection
COMSTAT status;
//Keep track of last error
DWORD errors;
public:
//Initialize Serial communication with the given COM port
Serial(char *portName);
//Close the connection
~Serial();
//Read data in a buffer, if nbChar is greater than the
//maximum number of bytes available, it will return only the
//bytes available. The function return -1 when nothing could
//be read, the number of bytes actually read.
int ReadData(char *buffer, unsigned int nbChar);
//Writes data from a buffer through the Serial connection
//return true on success.
bool WriteData(char *buffer, unsigned int nbChar);
//Check if we are actually connected
bool IsConnected();
};
#endif // SERIALCLASS_H_INCLUDED
CPP file (named SerialClass.cpp):
#include "SerialClass.h"
#include<iostream>
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 if (GetLastError() == ERROR_ACCESS_DENIED)
{
printf("It is this!!!!");
}
else
{
printf("ERROR!!!");
DWORD error = GetLastError();
std::cout << 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;
//Setting the DTR to Control_Enable ensures that the Arduino is properly
//reset upon establishing a connection
dcbSerialParams.fDtrControl = DTR_CONTROL_ENABLE;
//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;
//Flush any remaining characters in the buffers
PurgeComm(this->hSerial, PURGE_RXCLEAR | PURGE_TXCLEAR);
//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;
}
Example of usage (writing text to the serial):
Serial Arduino = Serial("COM3"); //My Arduino is at COM3 - change it for yours!
if (Arduino.IsConnected() == false) //Checks if it connected
{
std::cout << "Your Arduino isn't connected!" << std::endl;
std::cin.ignore();
return 1;
}
Arduino.WriteData("This is sent data"); //Sends "This is sent data" to the Serial which Arduino is connected to!
The Arduino should read data from the Serial (using the Serial class).
Note that your Arduino will have to be connected to the laptop via USB (not Wifi) for this to work . . .
Source: I did a project just like this!

Netduino communication with PC

I am new to netduino so I have a simple question (or, it should be simple).
What I want to do is to send an integer (string) via rs232 from my winform app to my netduino plus 2, and then, my netduino should read that integer and blink an onboard led that many times.
I have read online tutorial on that topic and found some examples that should provide communication between my PC and Netduino.
Yes, I did got an echo from it. I am getting an echo even if I disconnect my netduino and hide it in my pocket :).
So much for my understanding of that gadget.
How can I send an info to my Netduino via rs232 cabel that he can read, understand and act accordingly?
There is a code straight from the the web:
For NETDUINO:
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.Netduino;
using System.IO.Ports;
namespace NetduinoApplication1
{
public class Program
{
static SerialPort serial;
public static void Main()
{
// initialize the serial port for COM1 (using D0 & D1)
serial = new SerialPort(SerialPorts.COM1, 9600, Parity.None, 8, StopBits.One);
// open the serial-port, so we can send & receive data
serial.Open();
// add an event-handler for handling incoming data
serial.DataReceived += new SerialDataReceivedEventHandler(serial_DataReceived);
OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);
for (int i = 0; i < 3; i++)
{
led.Write(true); // turn on the LED
Thread.Sleep(250); // sleep for 250ms
led.Write(false); // turn off the LED
Thread.Sleep(250); // sleep for 250ms
}
// wait forever...
Thread.Sleep(Timeout.Infinite);
}
static void serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// create a single byte array
byte[] bytes = new byte[1];
// as long as there is data waiting to be read
while (serial.BytesToRead > 0)
{
// read a single byte
serial.Read(bytes, 0, bytes.Length);
// send the same byte back
serial.Write(bytes, 0, bytes.Length);
OutputPort led1 = new OutputPort(Pins.ONBOARD_LED, false);
led1.Write(true); // turn on the LED
Thread.Sleep(250); // sleep for 250ms
led1.Write(false); // turn off the LED
Thread.Sleep(250); // sleep for 250ms
}
}
}
}
And the code for my console:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
namespace ConsoleRSS
{
class Program
{
static SerialPort serial;
static void Main(string[] args)
{
// provide some usage information
System.Console.WriteLine("enter some text and hit ENTER.");
System.Console.WriteLine("enter 'x' and hit ENTER to exit.");
System.Console.WriteLine();
// initialize the serial port for COM3 (could be other port, depends on system)
serial = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
// open the serial-port, so we can send & receive data
serial.Open();
// add an event-handler for handling incoming data
serial.DataReceived += new SerialDataReceivedEventHandler(serial_DataReceived);
// this will hold each line entered
string line = string.Empty;
// as long as an x is not entered
while (line.ToLowerInvariant() != "x")
{
// read a single line from the console
line = System.Console.ReadLine();
// convert the line to bytes
byte[] utf8Bytes = System.Text.Encoding.UTF8.GetBytes(line);
// send the bytes over the serial-port
serial.Write(utf8Bytes, 0, utf8Bytes.Length);
}
}
static void serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// wait a little for the buffer to fill
System.Threading.Thread.Sleep(100);
// create an array for the incoming bytes
byte[] bytes = new byte[serial.BytesToRead];
// read the bytes
serial.Read(bytes, 0, bytes.Length);
// convert the bytes into a string
string line = System.Text.Encoding.UTF8.GetString(bytes);
// write the received bytes, as a string, to the console
System.Console.WriteLine("echo: " + line);
System.Console.WriteLine();
}
}
}
I'm not sure what problem you are actually getting with this? Your code at first glance looks correct.
I would try checking your hardware first, so is the usb cable actually set as COM 1 in device manager on your pc? Is the cable connected to the correct ports in the netduino?

Categories