display bytes greater than 0x7f - c#-4.0

I'd like to connect my program to a serial port & to show the received data from the serial port. I successfully did that, but I have a problem.
I'd like to convert the string shown in the window into a stream of bits
I followed How could I get the bits from a string in c#?
& my problem is what to do to show a byte like 0xAA, it's greater than 7f the maximum value of the ascii characters
I'm developing a program using C# language, I'd like to connect it to a serial port & to show the received data from the serial port,I successfully did that, but I have a problem, I'd like to convert the string shown in the window into a stream of bits I followed How could I get the bits from a string in C#?
& my problem is what to do to show a byte like 0xAA, it's greater than 7f the maximum value of the ASCII characters
public partial class mm_dig_ctrl : Form
{
public mm_dig_ctrl()
{
InitializeComponent();
if (!MySerP.IsOpen)
{
MySerP.Open();
TB_Port_Status.Text = "Port is Opened";
}
else
{
TB_Port_Status.Text = "Port is Busy";
}
MySerP.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(DataReceivedHandler);
}
public delegate void AddDataDelegate(String rxstring);
public AddDataDelegate myDelegate;
private void mm_dig_ctrl_Load(object sender, EventArgs e)
{
this.myDelegate = new AddDataDelegate(AddDataMethod);
}
public void AddDataMethod(String myString)
{
TBRX_Read.AppendText(myString);
}
private void DataReceivedHandler(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
String rxstring,to_show;
rxstring = MySerP.ReadExisting();
to_show = GetBits(rxstring);
TBRX_Read.Invoke(this.myDelegate, new object[] { to_show });
//TBRX_Read.Text += rxstring;
}
public string GetBits(string input)
{
StringBuilder sb = new StringBuilder();
foreach (byte b in input)
{
sb.Append(Convert.ToString(b, 16));
}
return sb.ToString();
}
'

Related

Sending Strings from arduino to Processing

I want to get Processing to read Strings from Arduino.
I send two Strings massages from the arduino and I want to store them in two different variables on Processing.
I tried to do it, but the two Strings are passed to the first variable and the second variable remains empty. I don't understand why this is the case. Can someone help?
Regards
Arduino Code
void setup() {
Serial.begin(9600);
delay(1000);
Serial.println("1.first message");
Serial.println("2.second message");
delay(100);
}
void loop() {
}
Processing Code
import processing.serial.*;
Serial myPort;
void setup() {
myPort=new Serial(this, "COM3", 9600);
}
void draw() {
String s1=myPort.readStringUntil('\n');
String s2=myPort.readStringUntil('\n');
// printing variables
if(s1!=null){
print("s1:",s1);
}
if(s2!=null){
println("s2:",s2);
}
}
The following works on my Mac system. The incoming strings are placed in a string array as they arrive. The string at index[0] then becomes s1 and the string at index[1] is s2. I also added a delay(100); between the two strings on the Arduino side, but this may not be necessary; you can try it both ways.
import processing.serial.*;
Serial myPort;
String[] s; // Array to hold two strings.
int counter = 0;
void setup() {
printArray(Serial.list()); // List of serial ports
// Enter appropriate number for your system
myPort = new Serial(this, Serial.list()[2], 9600);
s = new String[2];
println("===========");
}
void draw() {
String str = myPort.readStringUntil('\n');
if(str != null) {
s[counter] = str;
if(counter == 0){
println("s1 = ",s[0]);
} else {
println("s2 = ",s[1]);
}
counter++;
}
}

Cannot Append to Received String in UDP Listener C#

I have a Form that create a UDP object, in the UDP class a UDPClient is created and the received data is done in the BeginReceive Method using EndReceive.
When I print the string of the reveived data, after converting the byte[], to the console from within the beginreceive method, with text appended, only the received data prints not the appended text.
So it looks like the received data is incomplete.
When the string prints, the NewLine and appended "done" is not shown.
Any help would be great!!
Thanks
class Udp
{
public EventHandler _dataReceived;
public Udp()
{
int receiverPort = 1248;
UdpClient receiver = new UdpClient(receiverPort);
string discovery = "<?xml version=\"1.0\"?><ServiceQuery></ServiceQuery>";
receiver.BeginReceive(new AsyncCallback( DataReceived), receiver);
IPEndPoint end = new IPEndPoint(IPAddress.Broadcast, 1248);
receiver.Send(Encoding.ASCII.GetBytes(discovery + "\0"), discovery.Length + 1, end);
}
private void DataReceived(IAsyncResult ar)
{
UdpClient c = (UdpClient)ar.AsyncState;
IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 1248);
Byte[] receivedBytes = c.EndReceive(ar, ref receivedIpEndPoint);
string receivedText = ASCIIEncoding.ASCII.GetString(receivedBytes);
Console.WriteLine("\n");
if(_dataReceived != null)
{
Console.Write(receivedIpEndPoint + ": " + receivedText + Environment.NewLine + "done");
_dataReceived(receivedText, new EventArgs());
}
c.BeginReceive(new AsyncCallback(DataReceived), c);
}
}
The simplest repro I can think of for this problem is this code:
private void button1_Click(object sender, EventArgs e) {
Byte[] receivedBytes = new byte[] { 0x48, 0x65, 0x6c, 0x00, 0x6c, 0x6f };
string receivedText = Encoding.ASCII.GetString(receivedBytes);
Console.Write(receivedText + ", you won't see this");
}
Output after clicking the button several times:
HelHelHelHel
Surely you now recognize the poison-pill in the receivedBytes array, it is the presence of the 0x00 byte that causes the output string to get cut short. Nothing beyond that byte makes it into the Visual Studio Output window.
Explaining this behavior requires a pretty deep dive in how Console.Write() in a Winforms app works and how it is capable of generating output, even though your program has no console. It is a long-winded story that isn't that likely to entertain anybody so I'll punt for the short version. With the Visual Studio Hosting Process debugger option enabled, Console.Write() is equivalent to Debug.Write(). Debug output is intercepted by the DefaultTraceListener class, it pinvokes OutputDebugString() to get the text to appear in the debugger trace window. These winapi functions takes C strings, a C string is zero-terminated to indicate the end of the string.
There are several ways to fix this, the programmer's way is to convert the byte[] array content to hex:
Byte[] receivedBytes = new byte[] { 0x48, 0x65, 0x6c, 0x00, 0x6c, 0x6f };
string receivedText = BitConverter.ToString(receivedBytes);
Console.WriteLine(receivedText + ", you see this");
Output:
48-65-6C-00-6C-6F, you see this
48-65-6C-00-6C-6F, you see this
48-65-6C-00-6C-6F, you see this
Or you might want to take a better look at the data you transmit, ensuring it is actually printable text that can be properly converted with Encoding.ASCII

Sending strings over Serial to Arduino

I'm currently experimenting with sending a string to my Arduino Yun and trying to get it to reply back depending on what I send it.
I picked up a framework of some code here and have been experimenting with it but apart from the serial monitor displaying 'ready' I can't make it go any further.
The code is:
//declace a String to hold what we're inputting
String incomingString;
void setup() {
//initialise Serial communication on 9600 baud
Serial.begin(9600);
while(!Serial);
//delay(4000);
Serial.println("Ready!");
// The incoming String built up one byte at a time.
incomingString = "";
}
void loop () {
// Check if there's incoming serial data.
if (Serial.available() > 0) {
// Read a byte from the serial buffer.
char incomingByte = (char)Serial.read();
incomingString += incomingByte;
// Checks for null termination of the string.
if (incomingByte == '\0') {
// ...do something with String...
if(incomingString == "hello") {
Serial.println("Hello World!");
}
incomingString = "";
}
}
}
Can anyone point me in the right direction?
Thanks
I suspect the problem is that you're adding the null terminator onto the end of your string when you do: incomingString += incomingByte. When you're working with string objects (as opposed to raw char * strings) you don't need to do that. The object will take care of termination on its own.
The result is that your if condition is effectively doing this: if ("hello\0" == "hello") .... Obviously they're not equal, so the condition always fails.
I believe the solution is just to make sure you don't append the byte if it's null.
Try This:
String IncomingData = "";
String Temp = "";
char = var;
void setup()
{
Serial.begin(9600);
//you dont have to use it but if you want
// if(Serial)
{
Serial.println("Ready");
}
//or
while(!Serial)
{delay(5);}
Serial.println("Ready");
void loop()
{
while(Serial.available())
{
var = Serial.read();
Temp = String(var);
IncomingData+= Temp;
//or
IncomingData.concat(Temp);
// you can try
IncomindData += String(var);
}
Serial.println(IncomingData);
IncomingData = "";
}

Cast from int to String on android

I'm developing an app where I need to send the values of 3 seekbars via bluetooth. All the bluetooth method I've developed is based on the bluetoothChat example. The app communicates well sending characters, but as i said, i need to send the value of 3 seekbars.
So, I'm creating a sending function to send these 3 values in one string, but i think that i'm doing wrong the cast because i'm getting an error and the logcat refers my to this point.
This is the code, need to mention that the "savedProgressX" values are int type and have the current value of the seekbar, and the "sendX" values are textview type that I've created only to save these values:
public void sendValues() {
send1 = Integer.toString(savedProgress1);
send2 = Integer.toString(savedProgress2);
send3 = Integer.toString(savedProgress3);
/**Set the seekbars values into a string*/
String message = send1+":"+send2+":"+send3+"\n";
//String[] values = message.split(":");
//for (String value : values) {
//int number = Integer.valueOf(value);
//}
/**Check that we're actually connected before trying anything*/
if (GlobalVar.mTransmission.getState() != GlobalVar.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
/**Get the message bytes and tell the Transmission to write*/
byte[] send = message.getBytes();
GlobalVar.mTransmission.write(send);
/**Reset out string buffer to zero*/
GlobalVar.mOutStringBuffer.setLength(0);
}

LWUIT4IO (v1.5) ConnectionRequest's readResponse() Issue - Nokia SDK 2.0

I have been porting an existing J2ME mobile app, that allows users to view archived news videos, to the latest Nokia SDK 2.0 platform for Series 40 full-touch devices.
I am using both the LWUIT and LWUIT4IO technologies for the UI and Network functionalities of the application respectively.
The app has been tested to work on the S40 5th Edition SDK platform emulator. Extending LWUIT4IO's ConnectionRequest class and utilizing LWUIT's XMLParser, the app can successfully send a HTTP request and get the expected response data from a web service that basically returns an XML-formatted type of feed (containing necessary metadata for the video) (Here's the URL of the web service: http://nokiamusic.myxph.com/nokianewsfeed.aspx?format=3gp)
But for some reason, this is not the case when trying to run the app on the latest Nokia SDK 2.0 platform. It throws a java.lang.NullPointerException upon trying to parse (XMLParser.parse()) the InputStream response of the web service. When I trace the Network Traffic Monitor of the emulator of the corresponding Request sent and Response received - 0 bytes were returned as content despite a successful response status 200. Apparently the XMLParser object has nothing to parse in the first place.
I am hoping that you can somehow shed light on this issue or share any related resolutions, or help me further refine the problem.
Posted below is the code of the SegmentService class (a sub-class of LWUIT's ConnectionRequest) that connects to the webservice and processes the XML response:
public class SegmentService extends ConnectionRequest implements ParserCallback {
private Vector segments;
private Video segment;
public SegmentService(String backend) {
String slash = backend.endsWith("/") ? "" : "/";
setPost(false);
setUrl(backend + slash + "nokianewsfeed.aspx");
addArgument("format", "3gp");
}
public void setDateFilter(String date) {
System.out.println(date);
addArgument("date", date);
}
private Video getCurrent() {
if (segment == null) {
segment = new Video();
}
return segment;
}
protected void readResponse(InputStream input) throws IOException {
InputStreamReader i = new InputStreamReader(input, "UTF-8");
XMLParser xmlparser = new XMLParser();
System.out.println("Parsing the xml...");
Element element = xmlparser.parse(i);
System.out.println("Root " + element.getTagName());
int max = element.getNumChildren();
System.out.println("Number of children: " + max);
segments = new Vector();
for (int c = 0; c < max; c++) {
Element e = element.getChildAt(c);
System.out.println("segment " + c);
int len = e.getNumChildren();
System.out.println("Number of children: " + len);
for (int d=0; d<len; d++) {
Element s = e.getChildAt(d);
String property = s.getTagName();
System.out.println("key: " + property);
String value = (s.getNumChildren()>0) ? s.getChildAt(0).getText() : null;
System.out.println("value: " + value);
if (property.equals("title")) {
getCurrent().setTitle(value);
} else if (property.equals("description")) {
getCurrent().setDescription(value);
} else if (property.equals("videourl")) {
getCurrent().setVideoUrl(value);
} else if (property.equals("thumburl")) {
getCurrent().setThumbUrl(value);
} else if (property.equals("adurl")) {
getCurrent().setAdUrl(value);
} else if (property.equals("publishdate")) {
getCurrent().setPublishDate(value);
} else if (property.equals("category")) {
getCurrent().setCategory(value);
} else if (property.equals("weburl")) {
getCurrent().setWebUrl(value);
} else if (property.equals("thumburl2")) {
getCurrent().setThumb210(value);
} else if (property.equals("thumburl4")) {
getCurrent().setThumb40(value);
}
}
if (segment != null) {
segments.addElement(segment);
segment = null;
}
}
fireResponseListener(new NetworkEvent(this, segments));
}
public boolean parsingError(int errorId, String tag, String attribute, String value, String description) {
System.out.println(errorId);
System.out.println(tag);
System.out.println(value);
System.out.println(description);
return true;
}
}

Resources