C# and SerialPort formatting output - c#

I want to get position of my motor by using command "POS;", but I get this output "a ⌂▲ yI ° y" what with this if I can get numbers?
Then from time to time I get empty answer I was answered that it take some time to get output via Serial Port. What I have to add to my code to wait until I wil get full output to show?
Manual controller (update manual)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
SerialPort sp = new SerialPort();
sp.PortName = "COM1";
sp.BaudRate = 9600;
sp.Open();
sp.Encoding = System.Text.Encoding.GetEncoding(28591);
if (sp.IsOpen)
{
sp.Write("ENA;");
sp.Write("POS;");
string msgPos = sp.ReadExisting();
Console.WriteLine(msgPos);
sp.Write("OFF;");
sp.Close();
Console.ReadKey();
}
}
}
}

Just add a Thread.Sleep(50) betwen the send the write and the read command. 50 miliseconds should be enough if not try a longer time.
//Do something
sp.Write("POS;");
Thread.Sleep(50);
string msgPos = sp.ReadExisting();
//Do something else
I can't find any command POS; in the manual you posted. Do you mean FBK on page 15?

Related

C# MODBUS RTU for REGISTER READING

I am currently in the process of writing a c# program in VS where it reads the holding registers of a Panasonic KW9M-A Power Meter using Modbus-RTU. The holding register i'm trying to read is:
00A4H to 00A5H; Unsigned 32bit
Note: I wrote this in Console app. I used NModbus4 by Maxwe11
Idk what i'm missing since i'm a beginner in programming. Can someone please assist me? Thank you in advance :)
Here is what i have so far:
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Console_ye
{
class Program
{
public static void Main(string[] args)
{
SerialPort serialPort = new SerialPort("COM13", 115200, Parity.Odd, 8, StopBits.One);
serialPort.Open();
Console.WriteLine("This is the beginning: ");
string hex_add = "0x00A4";
ushort dec_add = Convert.ToUInt16(hex_add, 16);
Console.WriteLine("Value of hex: " + hex_add);
Console.WriteLine("Value of ushort: " + dec_add);
byte slaveId = 1;
ushort startAddress = dec_add;
ushort numberOfPoints = 8;
IModbusMaster masterRTU = ModbusSerialMaster.CreateRtu (serialPort);
ushort[] ushortArray = masterRTU.ReadHoldingRegisters(slaveId, startAddress, numberOfPoints);
Console.WriteLine("Here " + ushortArray[0]);
foreach (ushort item in ushortArray)
{
Console.WriteLine(string.Join ("\n", item));
}
}
}
}
Don't know anything about NModbus4, but as shown in the sample program, you'll probably need to include one or more of the following in your program.
using Modbus.Data;
using Modbus.Device;
using Modbus.Utility;
using Modbus.Serial;
You should correct the line:
Console.WriteLine(string.Join ("\n", item));
to
Console.WriteLine(item);
Then it'll be workable.

How to check and ignore message from serial port?

i want to ignore all messages that came to serial port except unique. i add each message to hashSet and when new message arrive i check that this messages not contains in hashSet, if this message not contains i want to print him, right now my program think that each messages arrived is unique and i don't understand why my comparing code not working, maybe somebody can help me. Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
namespace mySniffer
{
class Program
{
static void Main(string[] args)
{
HashSet<String> messages = new HashSet<String>();
SerialPort comPort = new SerialPort();
comPort.BaudRate = 115200;
comPort.PortName = "COM4";
comPort.Open();
while (true)
{
string rx = comPort.ReadLine(); //reading com port
messages.Add(rx); // Add new incoming message to hashSet
if (!messages.Contains(rx))
{
Console.WriteLine(rx); // write incoming message
}
else {
Console.WriteLine(messages.Count); // check how many messages in hashSet
}
}
}
}
}
The problem was in logic of code, messages.Add(rx); should be moved in if block.

How to get Monotorrents DHT to work?

Iam trying to get the dht implementation of monotorrent to work but i just cant seem to find any peers.
ive tried most of the examplecode code availeble on the net like the testclient and dhttest.
I have tried with several diffrent infohashes.
Anyone here got it working? or do you know where i can find the devs?
This is how my code looks atm:
using System;
using System.Collections.Generic;
using System.Text;
using MonoTorrent.Dht;
using MonoTorrent.Dht.Listeners;
using System.Net;
using System.IO;
using MonoTorrent.Common;
using MonoTorrent.Tracker.Listeners;
namespace SampleClient
{
class Program
{
static void Main(string[] args)
{
string basePath = Environment.CurrentDirectory;
string torrentsPath = Path.Combine(basePath, "Torrents");
Torrent torrent = null;
// If the torrentsPath does not exist, we want to create it
if (!Directory.Exists(torrentsPath))
Directory.CreateDirectory(torrentsPath);
// For each file in the torrents path that is a .torrent file, load it into the engine.
foreach (string file in Directory.GetFiles(torrentsPath))
{
if (file.EndsWith(".torrent"))
{
try
{
// Load the .torrent from the file into a Torrent instance
// You can use this to do preprocessing should you need to
torrent = Torrent.Load(file);
Console.WriteLine(torrent.InfoHash.ToString());
}
catch (Exception e)
{
Console.Write("Couldn't decode {0}: ", file);
Console.WriteLine(e.Message);
continue;
}
}
}
DhtListener listener = new DhtListener(new IPEndPoint(IPAddress.Parse("192.168.2.3"), 10000));
DhtEngine engine = new DhtEngine(listener);
//engine.RegisterDht(dht);
byte[] nodes = null;
if (File.Exists("mynodes"))
nodes = File.ReadAllBytes("mynodes");
listener.Start();
int i = 0;
bool running = true;
StringBuilder sb = new StringBuilder(1024);
while (running)
{
engine.Start(nodes);
while (Console.ReadLine() != "q")
{
engine.GetPeers(torrent.InfoHash);
}
File.WriteAllBytes("mynodes", engine.SaveNodes());
}
}
}
}
I know it's very old question, I'm not sure why it's still noone has answer it, anyway. The problem seem to be this line:
DhtListener listener = new DhtListener(new IPEndPoint(IPAddress.Parse("192.168.2.3"), 10000));
This ip is not the real ip, so you actually asl peers to send the respone to unkonw adress.
What to do? register your own adress.

how I can change the voice synthesizer gender and age in C#?

I would like to change the gender and age of the voice of System.Speech in c#. For example, a girl of 10 years but can not find any simple example to help me adjust the parameters.
First, check which voices you have installed by enumerating the GetInstalledVoices method of the SpeechSynthesizer class, and then use SelectVoiceByHints to select one of them:
using (SpeechSynthesizer synthesizer = new SpeechSynthesizer())
{
// show installed voices
foreach (var v in synthesizer.GetInstalledVoices().Select(v => v.VoiceInfo))
{
Console.WriteLine("Name:{0}, Gender:{1}, Age:{2}",
v.Description, v.Gender, v.Age);
}
// select male senior (if it exists)
synthesizer.SelectVoiceByHints(VoiceGender.Male, VoiceAge.Senior);
// select audio device
synthesizer.SetOutputToDefaultAudioDevice();
// build and speak a prompt
PromptBuilder builder = new PromptBuilder();
builder.AppendText("Found this on Stack Overflow.");
synthesizer.Speak(builder);
}
http://msdn.microsoft.com/en-us/library/system.speech.synthesis.voiceage.aspx
http://msdn.microsoft.com/en-us/library/system.speech.synthesis.voicegender.aspx
Did you take a look at this ?
first you need to intialise the reference speech using the add reference.
then create an event handler for the speak started then you can edit the paramemters inside that handler.
in the handler is where you can change the voice and age using the
synthesizer.SelectVoiceByHints(VoiceGender.Male , VoiceAge.Adult);
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Speech.Synthesis; // first import this package
namespace textToSpeech
{
public partial class home : Form
{
public string s = "pran"; // storing string (pran) to s
private void home_Load(object sender, EventArgs e)
{
speech(s); // calling the function with a string argument
}
private void speech(string args) // defining the function which will accept a string parameter
{
SpeechSynthesizer synthesizer = new SpeechSynthesizer();
synthesizer.SelectVoiceByHints(VoiceGender.Male , VoiceAge.Adult); // to change VoiceGender and VoiceAge check out those links below
synthesizer.Volume = 100; // (0 - 100)
synthesizer.Rate = 0; // (-10 - 10)
// Synchronous
synthesizer.Speak("Now I'm speaking, no other function'll work");
// Asynchronous
synthesizer.SpeakAsync("Welcome" + args); // here args = pran
}
}
}
It'll be better choice to use "SpeakAsync" because when "Speak" function is executing/running none of other function will work until it finishes it's work (personally recommended)
Change VoiceGender
Change VoiceAge
These age and gender is actually of no use. If you have many voices installed in your windows, then you may call specific voices by these parameters. Otherwise, its simply fake!

SharpSSH - SSHExec, run command, and wait 5 seconds for data!

I have this code:
using System;
using System.Text;
using Tamir.SharpSsh;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
SshExec exec = new SshExec("192.168.0.1", "admin", "haha");
exec.Connect();
string output = exec.RunCommand("interface wireless scan wlan1 duration=5");
Console.WriteLine(output);
exec.Close();
}
}
}
The command will execute! I can see that, but! It immediately prints data. Or actually, it does'nt print the data from the command. It prints like the... logo for the mikrotik os. I actually need the data from the command, and I need SharpSSH to wait at least 5 seconds for data, then give it back to me...
Somebody knows how I can do this?
I'm pretty new to this! I appreciate all help! Thank you!
You may want to try the following overload:
SshExec exec = new SshExec("192.168.0.1", "admin", "haha");
exec.Connect();
string stdOut = null;
string stdError = null;
exec.RunCommand("interface wireless scan wlan1 duration=5", ref stdOut, ref stdError);
Console.WriteLine(stdOut);
exec.Close();
If their API does what the name implies, it should put the standard output of your command
in stdOut and the standard error in stdError.
For more information about standard streams, check this out: http://en.wikipedia.org/wiki/Standard_streams

Categories

Resources