Im trying to send a string over an serial port using C#.
I've accomplished to send this string via the terminal on my RaspBerry pi ( Raspbian) using the following command:
echo "TestMode On" > /dev/ttyAMC0
This works! but this is in the terminal only. What I would like to do is execute this specific command using C# What my current approach is is this :
public bool DoSomething(){
MySerial = new SerialPort("/dev/ttyACM0");
MySerial.Open();
MySerial.ReadTimeout = 400;
string s = "echo \"TestMode On\"\r";
Log.Information(s);
return SendData(s);
}
private bool SendData(string command)
{
MySerial.Write(command);
return true;
}
I'm Using Serilog to log information and in that console window I can see that the string really is:
echo "TestMode On"
What am I missing here?.
Thanks in advance,
Herm L.
Echo sends a newline by default and you would not include the quotes:
This line:
string s = "echo \"TestMode On\"\r";
Becomes:
string s = "TestMode On\n";
The solution in this case is to change the encoding on the serial port from ASCII to UTF8. Apperantly this makes a difference here. Thanks everyone for their time and efforts!
Related
I'm trying to get a tow-way communication between a c# application and a python script that c# will call.
I have some input channels in c# that changes constantly at high frequency (5000-1000 data/s) for let's say a minute. On every change of those inputs,results are calculated and assigned to output variables. What i'm trying to do is to move the logic to a python script. For instance:
Inputs: double x,y
Output: double z
So the pyhton script should be capable of read the inputs, perform the logic and write the results at a symilar frequency.
Any recomendations? Has anyone did anything similar before?
First I tried to call the script on every change and read the console output. But the code in the script is not as simple as z=x*y and variables that store values are required in the pyhon script. For example, the script mught want to save the maximum value of x and y reached.
I had a look to ZeroMQ library for the communication, not sure how to use it though.
Here is a solution:
Simple C# program: client which sends data and receive
using System;
using ZeroMQ;
namespace ZeroMQ_Client
{
class Program
{
static void Main(string[] args)
{
using (var requester = new ZSocket(ZSocketType.REQ))
{
// Connect
requester.Connect("tcp://127.0.0.1:5555");
for (int n = 0; n < 10; ++n)
{
string requestText = "Hello";
Console.Write("Sending {0}...", requestText);
// Send
requester.Send(new ZFrame(requestText));
// Receive
using (ZFrame reply = requester.ReceiveFrame())
{
Console.WriteLine(" Received: {0} {1}!", requestText, reply.ReadString());
}
}
}
}
}
}
python program, you have to install pyzmq:
#
# Hello World server in Python
# Binds REP socket to tcp://*:5555
# Expects b"Hello" from client, replies with b"World"
#
import time
import zmq
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://*:5555")
while True:
# Wait for next request from client
message = socket.recv()
print("Received request: %s" % message)
# Do some 'work'
time.sleep(1)
# Send reply back to client
socket.send(b"World")
I am trying to capture the net weight from a IND560 using C#'s streamReader and streamWriter classes. It seems a connection is made, but no matter the command I send, I get a response back: 83 Command not recognized. I see the command (wt0111) in the IND560 under Communications>Template>output for template1.
The code is below if anyone has any suggestions to help me move forward it would be much appreciated!
static void writeToStream(string cmd)
{
if (tcpClient.Connected)
{
Console.WriteLine("Sending CMD: {0}\\n", cmd);
// tried with appending a \r, \n, and \r\n same result: 83 command not found
clientStreamWriter.Write(cmd + '\n');
clientStreamWriter.Flush();
}
}
Here is a sample output of the program showing the response 83:
You would need to use read command for the purpose (according to link here)
Format: read SDV#1 SDV#2
Example 1: read wt0101 wt0103
Response 1: 00R003~ 17.08~lb~
So, in your case
read wt0101
read wt0111
In your case you would need to prepend "read" before the field ID (wt0101).
if (tcpClient.Connected)
{
Console.WriteLine("Sending CMD: {0}\\n", cmd);
clientStreamWriter.Write($"read {cmd}" + '\n');
clientStreamWriter.Flush();
}
I would suggest to provide your users an option to input the command to "read" "write", "help", along with field name, in case you are intending to support more command.
I am trying to get data from my MySQL server to my Unity project. I tried to get the data like so:
public string awsurl = "ec2-174-129-82-141.compute-1.amazonaws.com/connect_to_server.php";
IEnumerator GetScores()
{
print("get scores start");
WWW aws_get = new WWW(awsurl);
yield return aws_get;
print("getscore here");
if (aws_get.error != null)
{
print("There was an error getting aws: " + aws_get.error);
}
else
{
print(aws_get.text); // this is a GUIText that will display the scores in game.
}
}
I have a php script on my server to handle the interaction because I am having trouble using the MySqlConnection library for my unity project.
Here is my php script:
$address = "localhost"
$dbusername = "root";
$dbpassword = "root";
$db_name = "watshoes";
$db_conn = new mysqli($address, $dbusername, $dbpassword, $db_name);
if(isset($_POST['username'])) $username = $_POST['username'];
if(isset($_POST['user_id'])) $user_id = $_POST['user_id'];
if(isset($password)) $password =$_POST['password'];
$stmt = $db_conn->prepare("SELECT image FROM ImageText");
// "s" means the database expects a string
$stmt->bind_param("s", $user_id);
if($stmt->execute())
{
/* bind result variables */
$stmt->bind_result($image);
/* fetch value */
$stmt->fetch();
echo $image;
}
else
{
echo "query failed";
}
$stmt->close();
$db_conn->close();
But every time I run the code I get this error:There was an error getting aws: Failed to connect to ec2-174-129-82-141.compute-1.amazonaws.com port 80: Timed out
Thanks for looking at the code and please let me know if there is anything else I can do to help.
You have to add a rule to open the port 80 using security groups (Inbound tab)
How your rule should look:
By default the port 80 is close in EC2 AWS instances.
And the URL is malformed in Unity
Add http:// to your server URL
In editor will work ok without http:// but it will fail in android.
I'm trying to print on Olivetti PR 4 SL. In of out .NET application ("Print Test Page", Word, ...) it works. But in my .NET application, it doesn't.
This is my simplified code:
using (var serialPort = new SerialPort())
{
serialPort.PortName = "COM1"; // Where the printer is installed.
serialPort.Open();
serialPort.Write("Hello world!");
}
The error message is:
The given port name does not start with COM/com or does not resolve to
a valid serial port. Parameter name: portName
Would anyone help me to solve this problem?
You need to finalize the character stream which are sent to the printer by NEW_LINE (ASCII code is 10).
You can use the following line of code in order to print;
serialPort.Write(new byte[] { 10 });
I'm trying to convert TCL code, used to communicate with a serial port to a "robot", to C#. But for some reason my commands are not getting responses.
This is the serial com init in TCL:
proc openUart {} {
set robot::fd_ [open COM${robot::port_num}: w+]
fconfigure $robot::fd_ -mode 9600,e,7,1
fconfigure $robot::fd_ -blocking 0
fconfigure $robot::fd_ -buffering none
fileevent $robot::fd_ readable ""
}
A "command" is sent like this:
proc SendCmd {command} {
set commandlen [string length $command]
for {set i 0} {$i < $commandlen} {incr i} {
set letter [string index $command $i]
after 10
puts -nonewline $robot::fd_ $letter
}
after [expr 2 * 10]
puts -nonewline $robot::fd_ "\n"
flush $robot::fd_
}
This is how I translated this to C#. Opening the port:
private void Initialize(string com)
{
_comPort = new SerialPort(com,9600,Parity.Even,7,StopBits.One)
{
Encoding = Encoding.ASCII,
NewLine = "\n"
};
_comPort.Open();
}
And sending a command:
private string SendCommand(Commands cmd)
{
string commandToWrite = Command(cmd);
for (int i = 0; i < CommandLen; i++)
{
Thread.Sleep(10);
_comPort.Write(commandToWrite.ToCharArray(), i, 1);
}
Thread.Sleep(10 * 2);
_comPort.Write("\n");
_comPort.BaseStream.Flush();
}
I connected my PC to the robot with a serial to USB cable and ran both TCL and C# programs -
The TCL script turns on a LED on the robot.
My C# code doesn't turn the LED on, meaning the robot did not recognize the command.
I'm using the same com port, so I believe the problem is one of these:
I did not initialize the com port correctly in C#. How do you set the blocking and buffering?
Could there be an encoding issue in C#? isn't ASCII the default encoding in TCL?
Could there be a timing difference in how I'm sending the command letter-by-letter between the two languages?
Issue resolved!
I finally looped back the cable into my PC using another serial cable and 2 blue wires, crossing the RX\TX (thanks don_q for the idea!).
Using a simple serial monitor, "UART Terminal", I sniffed the commands, and to my surprise the TCL script was adding a '\r' before the '\n'!
So in fact the robot was expecting this command format -
:010508010000F1\r\n
I changed the NewLine property in C# to be "\r\n", and now I finish a command by using -
_comPort.WriteLine("");
And now everything works.