I am trying to interface my C# Windows Forms application from my laptop to the Arduino Duemilanove. A Bluetooth module is connected to the Tx and Rx pins on the Arduino. My goal is to light up the on-board LED when I type in the letter 'a' and so far it has been unsuccessful. I am sure the Bluetooth is connected with my laptop, but it is not responding to the letter I am pressing.
C# code
public partial class Form1 : Form
{
private Guid service = BluetoothService.SerialPort;
private BluetoothClient bluetoothClient;
public Form1()
{
InitializeComponent();
this.KeyPreview = true;
this.KeyPress += new KeyPressEventHandler(Form1_KeyPress);
}
void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 'a')
{
Stream peerStream = bluetoothClient.GetStream();
Byte[] buffer = Encoding.ASCII.GetBytes("a");
peerStream.Write(buffer, 0, buffer.Length);
}
}
private void search_Click(object sender, EventArgs e)
{
BluetoothRadio.PrimaryRadio.Mode = RadioMode.Discoverable;
BluetoothRadio myRadio = BluetoothRadio.PrimaryRadio;
bluetoothClient = new BluetoothClient();
Cursor.Current = Cursors.WaitCursor;
BluetoothDeviceInfo[] bluetoothDeviceInfo = { };
bluetoothDeviceInfo = bluetoothClient.DiscoverDevices(10);
comboBox1.DataSource = bluetoothDeviceInfo;
comboBox1.DisplayMember = "DeviceName";
comboBox1.ValueMember = "DeviceAddress";
comboBox1.Focus();
Cursor.Current = Cursors.Default;
}
private void Connect_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedValue != null)
{
try
{
bluetoothClient.Connect(new BluetoothEndPoint((BluetoothAddress)comboBox1.SelectedValue, service));
MessageBox.Show("Connected");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
Arduino Code
int incomingByte = 0; // For incoming serial data
void setup()
{
pinMode(13, OUTPUT); // On-board LED as output
Serial.begin(9600); // Opens serial port, sets data rate to 9600 bit/s.
}
void loop()
{
if (Serial.available() > 0)
{
// Read the incoming byte:
incomingByte = Serial.read();
if (incomingByte == 'a')
digitalWrite(13, HIGH);
}
}
Am I sending the ASCII code wrongly or what am I missing?
May be the same issue as I answered here.
I recently dabbled into this. The Arduino automatically resets when it
receives serial communication from most things other than the Arduino
IDE. This is why you can send from the IDE but not node.js.
I have an Uno and put a capacitor between Reset and Ground.Here's a
page with some good info on the subject. Good luck.
http://arduino.cc/playground/Main/DisablingAutoResetOnSerialConnection
Related
I am trying to retrieve weight data from a weight indicator which sends data through the RS232 com port ( Converted through USB)
following is the application I designed to receive data
enter image description here
the problem is it shows all the data which is sent from the indicator but the real weight reading is 15,000.
How can I achieve this?
Thank you
Data sheet of the indicator is as follows
Code is as follows
namespace Weight_Test
{
public partial class Form1 : Form
{
string dataIN;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string[] ports = SerialPort.GetPortNames();
cbComPort.Items.AddRange(ports);
btnOpen.Enabled = true;
btnClose.Enabled = false;
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
dataIN = serialPort1.ReadExisting();
this.Invoke(new EventHandler(ShowData));
}
private void ShowData(object sender, EventArgs e)
{
txtWeight.Text = dataIN;
}
private void btnOpen_Click(object sender, EventArgs e)
{
try
{
serialPort1.PortName = cbComPort.Text;
serialPort1.BaudRate = Convert.ToInt32(9600);
serialPort1.DataBits = Convert.ToInt32(8);
serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), "One");
serialPort1.Parity = (Parity)Enum.Parse(typeof(Parity), "None");
serialPort1.Open();
btnOpen.Enabled = false;
btnClose.Enabled = true;
}
catch (Exception err)
{
MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
btnOpen.Enabled = true;
btnClose.Enabled = false;
}
}
private void btnClose_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
btnOpen.Enabled = true;
btnClose.Enabled = false;
}
}
}
}
It all seems to work properly. All you need is processing of received data.
You said that your result should be 15,000.
Depends on what sensor you use, it can supply specified resolution, accuracy. Please edit your post and give us some information from datasheet about sending data.
Since you got "+01500001F🥹", it looks like you have 15,000.01, which very is good, but of course I can't be sure.
All you have to do is to process these data. If you have it in string format, you should use Substring method to get rid of decimal places.
For example, with:
string receivedText = DataIN.Substring(0,7);
You'll get "+015000", which you can easily convert to Int32 value, using:
int receivedValue = Convert.ToInt32(receivedText);
And you'll finally get your 15000 as integer.
I'm working on windows forms app with communication with microcontroler. Previously my project was based on arduino nano and it worked flawlessly. Right now I'm switching to STM32 with arduino core (STM32duino) and I have got problem with receiving data through serial in windows forms app. Right now I'm testing that with nucelo32 L432 board while being connected to Serial(0) port of that board. Let's start with my arduino code:
extern "C" void SystemClock_Config(void) {
RCC_OscInitTypeDef RCC_OscInitStruct = {};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {};
RCC_PeriphCLKInitTypeDef PeriphClkInit = {};
/* Initializes the RCC Oscillators according to the specified parameters
in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI;
RCC_OscInitStruct.MSIState = RCC_MSI_ON;
RCC_OscInitStruct.MSICalibrationValue = 0;
RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_6;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_MSI;
RCC_OscInitStruct.PLL.PLLM = 1;
RCC_OscInitStruct.PLL.PLLN = 40;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV7;
RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
Error_Handler();
}
/* Initializes the CPU, AHB and APB buses clocks */
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK |
RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK) {
Error_Handler();
}
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USB;
PeriphClkInit.UsbClockSelection = RCC_USBCLKSOURCE_PLLSAI1;
PeriphClkInit.PLLSAI1.PLLSAI1Source = RCC_PLLSOURCE_MSI;
PeriphClkInit.PLLSAI1.PLLSAI1M = 1;
PeriphClkInit.PLLSAI1.PLLSAI1N = 24;
PeriphClkInit.PLLSAI1.PLLSAI1P = RCC_PLLP_DIV7;
PeriphClkInit.PLLSAI1.PLLSAI1Q = RCC_PLLQ_DIV2;
PeriphClkInit.PLLSAI1.PLLSAI1R = RCC_PLLR_DIV2;
PeriphClkInit.PLLSAI1.PLLSAI1ClockOut = RCC_PLLSAI1_48M2CLK;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK) {
Error_Handler();
}
/* Configure the main internal regulator output voltage */
if (HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1) != HAL_OK) {
Error_Handler();
}
}
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
Serial.begin(9600);
}
void loop() {
if (Serial.available()) {
Serial.println("A");
digitalWrite(LED_BUILTIN, HIGH);
}
}
As you can see first it initialize clocks so that serial is visible as Virtual com port in PC then initialize serial with baud rate of 9600, and LED_BUILTIN pin. Then when it will receive any serial data it should output to serial letter "H" and turn LED ON.
I upload that to board and test with arduino serial monitor and PuTTy - works as expected - as soon as it received anything through serial it outputs "h" and onboard LED turns ON.
Now let's get to my windows forms test app. It's just a simple form with comboBox to select com port that I'd like to connect to, refresh button to refresh com ports list, connect button that will initialize connection, send button that will send "H" through serial and label to show "Received something" when it will receive anything through serial:
Form layout
And code for that form:
public partial class Form1 : Form
{
string IncomingData;
public Form1()
{
InitializeComponent();
serialPort1.DataReceived += serialPort1_DataReceived;
foreach (string s in System.IO.Ports.SerialPort.GetPortNames())
{
comboBox1.Items.Add(s);
}
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
IncomingData = serialPort1.ReadLine();
this.Invoke(new EventHandler(ReceivedDataHandle));temperatury
}
private void ReceivedDataHandle(object sender, EventArgs e)
{
label1.Text = "Received something";
}
private void button1_Click(object sender, EventArgs e)
{ //connect button
try
{
serialPort1.BaudRate = 9600;
serialPort1.PortName = comboBox1.Text;
serialPort1.NewLine = "\r\n";
serialPort1.Open();
Thread.Sleep(1000);
MessageBox.Show("Connected");
}
catch (Exception)
{
MessageBox.Show("Error - connection problem");
}
}
private void button2_Click(object sender, EventArgs e)
{ //Send button
try
{
serialPort1.WriteLine("H");
}
catch (Exception)
{
MessageBox.Show("Error - connection problem");
}
}
private void button3_Click(object sender, EventArgs e)
{ //refresh button - get com ports
comboBox1.Items.Clear();
foreach (string s in System.IO.Ports.SerialPort.GetPortNames())
{
comboBox1.Items.Add(s);
}
}
}
I have tested that with Arduino NANO and it works as it should - after arduino receive "H" through serial it sends through serial "A", turns onboard LED on and label1 text changes to "Received something", but with nucleo board something weird happens...
After pressing send button, LED on nucleo board turns on, so it has received "H", but label1 forms app doesn't receive anything back - label1 doesn't change text. Also I have put breakpoint in line:
IncomingData = serialPort1.ReadLine();
Then with arduino app stops and goes into "debug checking" and with nucleo it doesnt, so I assume forms doesn't receive any data.
Then... what I can try? How to solve that?
##UPDATE:
Problem probably solved. I had to add serialPort1.DTREnabled = true and serialPort1.RTSEnabled = true.
I forgot that stm32duino doesn't handshake...
Will do more testing and raport back if there will be any problems.
As suggested - here is solution:
I had to add serialPort1.DtrEnabled = true and serialPort1.RtsEnabled = true, because STM32duino doesn't do handshake. Now it is working as it should.
There's some outdated software that's used to control the scoreboard at my local athletics track and I've been tasked with creating a new advanced one. However, I cannot seem to get the scoreboard to do what I ask it to do.
I've installed the original software to the my laptop and it works fine, however, when I run my test software that sends data to the board through the serial port, it isn't doing what I want.
I have the "Scoreboard Data Protocol" supplied by the manufacturer and I've been following this. I will supply the code to my test program that I've been using to see if I can get it to work and I will also supply the Data Protocol.
In the text box, I type 010D0201SPAIN and 003C630 and send it to the board and this doesn't work.
public partial class Form1 : Form
{
private SerialPort m_port;
public Form1()
{
InitializeComponent();
m_list.Items.AddRange(SerialPort.GetPortNames()); // Adds ports to combobox
m_port = new SerialPort();
m_port.BaudRate = 9600;
m_port.DataBits = 8;
m_port.Parity = Parity.Even;
m_port.StopBits = StopBits.One;
//m_port.Handshake = Handshake.None;
m_port.Encoding = new ASCIIEncoding();
m_port.RtsEnable = true;
m_port.DtrEnable = true;
m_port.ReceivedBytesThreshold = 1;
m_port.DataReceived += DataReceivedEvent;
}
private void button1_Click(object sender, EventArgs e)
{
m_port.Close();
m_port.PortName = (string)m_list.SelectedItem;
try
{
m_port.Open();
m_sendbutton.Enabled = true;
button2.Enabled = true;
}catch(UnauthorizedAccessException ex)
{
MessageBox.Show(ex.Message);
}
}
private void m_sendbutton_Click(object sender, EventArgs e)
{
m_port.Write(m_textbox.Text);
}
private void DataReceivedEvent(object sender, SerialDataReceivedEventArgs args)
{
Invoke(new EventHandler(DoUpdate));
}
private void DoUpdate(object s, EventArgs e)
{
label1.Text += m_port.ReadLine();
}
private void button2_Click(object sender, EventArgs e)
{
byte[] r_bytes = Encoding.ASCII.GetBytes(m_textbox.Text);
m_port.Write(r_bytes, 0, r_bytes.Length);
}
}
}
Scoreboard Data Protocol
Code: https://hastebin.com/epirobuduv.cs
Here's how to add STX and ETX around your message, in a byte array.
private void button2_Click(object sender, EventArgs e)
{
var msg = Encoding.ASCII.GetBytes(m_textbox.Text).ToList();
msg.Insert(0, 0x02); // STX at the start
msg.Add(0x03); // ETX at the end
m_port.Write(msg.ToArray(), 0, msg.Count);
}
I created application for reading from Serial Port and it works just fine. But the problem occure when I close the application and run it again. Suddenly reading from Serial port stops working. I have to disconnect and connect USB to fix that.
This is my code:
namespace Serial
{
public partial class Main : Form
{
SerialPort mainSerialPort = new SerialPort();
public Main()
{
InitializeComponent();
}
delegate void SetTextCallback(string text);
private void buttonOpen_Click(object sender, EventArgs e)
{
mainSerialPort.PortName = "COM" + numericPort.Value.ToString();
mainSerialPort.BaudRate = 115200;
mainSerialPort.Parity = Parity.None;
mainSerialPort.StopBits = StopBits.One;
mainSerialPort.DataBits = 8;
mainSerialPort.Handshake = Handshake.None;
mainSerialPort.DataReceived += DataReceived_Read;
try{
mainSerialPort.Open();
}catch (Exception ex){
labelStatus.Text = ex.GetType().ToString();
}
if (mainSerialPort.IsOpen == true){
numericPort.BackColor = Color.Green;
labelStatus.Text = "Port je otevřen!";
}else{
numericPort.BackColor = Color.Red;
}
}
private void DataReceived_Read(object sender, SerialDataReceivedEventArgs e)
{
SerialPort mySerial = (SerialPort)sender;
if (this.InvokeRequired){
listBoxRead.Invoke(new MethodInvoker(delegate {
listBoxRead.Items.Add(mySerial.ReadExisting());
listBoxRead.SelectedIndex = listBoxRead.Items.Count - 1;
}));
}
}
private void Main_FormClosed(object sender, FormClosedEventArgs e)
{
mainSerialPort.DataReceived -= DataReceived_Read;
mainSerialPort.Close();
}
}
}
USB and serial ports are unmanaged ressources. You have to dispose it!. A simple "Close" on FormClosed will not do the same.
I think it has to do with some resources not properly freed up. Try calling Dispose method
mainSerialPort.Close();
mainSerialPort.Dispose();
i am develop application for getting weight from weigh Bridge machine using C#.Net.i am trying lot of ways but,doesn't read correct data format weight from weigh bridge machine.i am getting ouput like ?x???????x?x?x??x???x??x???x???x? continuously get from serial port.i want to get weight from weigh bridge machine my code is listed below:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;
namespace SerialPortTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
String a = "";
private void button1_Click(object sender, EventArgs e)
{
serialPort1 = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
if (serialPort1.IsOpen == false)
{
serialPort1.Open();
}
timer1.Start();
button1.Enabled = false;
button2.Enabled = true;
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
a = a + serialPort1.ReadExisting();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (a.Length != 0)
{
textBox1.AppendText(a);
a = "";
}
}
private void button2_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen == true)
{
serialPort1.Close();
button2.Enabled = false;
button1.Enabled = true;
}
}
private void Form1_Load(object sender, EventArgs e)
{
if (serialPort1.IsOpen == true)
{
button1.Enabled = false;
button2.Enabled = true;
}
else
{
button1.Enabled = true;
button2.Enabled = false;
}
}
}
}
my code is append text from serial port data to textbox but,it's shows only like ?xxx?xxxx?xxxx?
can any one help me how to get weight from serial port using c#
Thanks For Reading My Post!
You are using ReadExisting(), that method tries to convert the bytes received by the port into a string. You'll get a question mark if that conversion fails. The default Encoding is ASCII, a byte value between 128 and 255 is not an ASCII character and thus produces a ?
Several possible reasons, roughly in order of likelihood:
Using the wrong baud rate, in particular guessing too high.
The device might be sending binary data, not strings. Which requires using Read() instead of ReadExisting and decoding the binary data.
Electrical noise picked up by a long cable that isn't shielded well enough. Easy to eliminate as a possible reason by disconnecting the cable at the bridge end. If that stops the data then it isn't likely to be noise.
Be sure to thoroughly read the manual. Contact the vendor of the device if you don't have one or can't make sense of it.
This code will be reading weightbridge continuously in background. Be sure to connect the pc with serial port. Also in design page Form1.cs[Design] you need to add Serial port from the toolbox. This code works for me, I hope it works for you too...
public partial class Form1 : Form
{
//Initialize the port and background Worker
private SerialPort port;
private BackgroundWorker backgroundWorker_Indicator;
public Form1()
{
backgroundWorker_Indicator = new BackgroundWorker();
backgroundWorker_Indicator.WorkerSupportsCancellation = true;
backgroundWorker_Indicator.DoWork += new DoWorkEventHandler(Indicator_DoWork);
//set the port according to your requirement.
port = new SerialPort("COMM2", 2400, Parity.None, 8, StopBits.One);
port.DataReceived += new SerialDataReceivedEventHandler(this.Indicator_DataReceived);
}
//button which starts the method. You can also put the method in Form1_Load()
private void SerialPortButton(object sender, EventArgs e)
{
StartStopIndicator();
}
private void StartStopIndicator()
{
try
{
port.Open();
backgroundWorker_Indicator.RunWorkerAsync();
}catch (Exception ea)
{
MessageBox.Show("13 "+ea.Message);
}
}
// Not a button. Just a methood.
private void Indicator_DoWork(object sender, DoWorkEventArgs e)
{
}
private void Indicator_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
string str = StripNonNumeric(port.ReadLine());
UpdateWeightOnUI(str);
}
catch (Exception eb)
{
MessageBox.Show("12"+eb.Message);
}
}
private void UpdateWeightOnUI(string Weight)
{
try
{
// A label named weightLabel from the toolbox. This will keep updating on weight change automatically
if (weightLabel.InvokeRequired)
{
this.Invoke((Delegate)new Form1.SetTextCallBack(this.UpdateWeightOnUI), (object)Weight);
}
else
{
weightLabel.Text = Weight;
}
}
catch (Exception ec)
{
MessageBox.Show("11"+ec.Message);
}
}
// This method will remove all other things except the integers
private string StripNonNumeric(string original)
{
StringBuilder stringBuilder = new StringBuilder();
foreach (char c in original)
{
if (char.IsDigit(c))
stringBuilder.Append(c);
}
return stringBuilder.ToString();
}
private delegate void SetTextCallBack(string text);