Currently my android bluetooth device receive character one by one. Is it possible for me to receive one shot together without one by one ? Thanks for advice.
For example incoming data:
abcd but incoming one by 1 like a b c d
how to make it like:
abcd incoming abcd straight away.
I need to change this line code?
message = txtReceived.getText().toString() + (char)data;}
This is my current code.
btnSend.setOnClickListener(this);
int delay = 1000; // delay in ms
int period = 100; // repeat in ms
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
if (flag)
{
final byte data = read();
readMessageHandler.post(new Runnable()
{
public void run()
{
String message;
if (data != 1){
/* if(txtReceived.getText().toString().equals("ON") || txtReceived.getText().toString().equals("OFF"))
{
txtReceived.setText("");
}*/
message = txtReceived.getText().toString() + (char)data;}
else{
message = "";}
txtReceived.setText(message);
}
});
}
}
}, delay, period);
private byte read()
{
byte dataRead = 0;
try
{
dataRead = (byte) inputStream.read();
}
catch(IOException readException)
{
toastText = "Failed to read from input stream: " + readException.getMessage();
Toast.makeText(Blood_Pressure.this, toastText, Toast.LENGTH_SHORT).show();
}
return dataRead;
}
The problem is that inputstream.read returns only one byte of data, hence, you are reading byte-by-byte.
You can send the size of message before the message and then send the message.
You can modify the code to something like this.
{
...
// assuming size is within the range of integer
byte[] sizeOfIncomingData = new byte[4];
inputStream.read(sizeOfIncomingdata, 0, 4);
int size = getIntFromByteArray(sizeOfIncomingData);
byte[] dataBuffer = new byte[size];
inputStream.read(dataBuffer, 0, size);
String message = new String(dataBuffer, "UTF-8");
}
private int getIntFromByteArray(byte[] bytes)
{
return (bytes[0] & 0xFF) << 24 | (bytes[1] & 0xFF) << 16 | (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF);
}
Related
I am reading and writing to an RFID tag using MFRC522.h
I can currently read the UID of a card and dump it to "UIDChar"
The UID of a card typically is 8 characters.
UID Example: 467EE9A9
I can use the mfrc522.MIFARE_SetUid function to write this UID to a new card. In order to do this I have to set the newUID to:
0x46,0x7E,0xE9,0xA9f
I have written this into my code.
What I am wanting to do is convert the UID string into a byte array so that I can use that in place of my manually written 0x46,0x7E,0xE9,0xA9.
I use the convert function to convert the UID into that format.
It can that be displayed with "buf".
Serial.println(buf);
Now my problem. If I replace the
byte newUid[] = {0x46,0x7E,0xE9,0xA9f};
with
byte newUid[] = {buf};
I get the error
invalid conversion from 'char*' to 'byte {aka unsigned char}'
How can I set my "newUid" as "buf"?
#define SS_PIN 0 //D2
#define RST_PIN 2 //D1
#include <SPI.h>
#include <MFRC522.h>
/* For RFID */
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
char buf[40]; // For string to byte array convertor
void convert(char *s)
{
int i, j, k;
buf[0] = 0x0;
for (j = 0, i = 0, k = 0; j < strlen(s); j++)
{
if (i++ == 0) {
buf[k++] = '0';
buf[k++] = 'x';
}
buf[k++] = s[j];
if (i == 2) {
if(j != strlen(s) -1) buf[k++] = ',';
i = 0;
}
}
buf[k] = 0x0;
}
void clone() {
/* RFID Read */
// Look for new cards
if ( ! mfrc522.PICC_IsNewCardPresent())
{
return;
}
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial())
{
return;
}
//Show UID on serial monitor
Serial.println();
Serial.print(" UID tag :");
// Very basic UID dump
unsigned int hex_num;
hex_num = mfrc522.uid.uidByte[0] << 24;
hex_num += mfrc522.uid.uidByte[1] << 16;
hex_num += mfrc522.uid.uidByte[2] << 8;
hex_num += mfrc522.uid.uidByte[3];
// Get UID
int NFC_id = (int)hex_num;
Serial.print(NFC_id, HEX);
// Convert UID to string using an int and a base (hexadecimal)
String stringUID = String(NFC_id, HEX);
char UIDChar[10];
stringUID.toCharArray(UIDChar,10);
delay(1000);
Serial.println();
// Convert to uppercase
for (int i = 0; i < strlen(UIDChar); i++ )
{
if ( UIDChar[i] == NULL ) break;
UIDChar[i] = toupper(UIDChar[i]);
}
//Serial.print( &UIDChar[0] );
Serial.println();
convert(UIDChar);
Serial.println(buf);
/* RFID Write */
// Set new UID
// Change your UID hex string to 4 byte array
// I get error if I use byte newUid[] = {buf};
/* ERROR HERE */
byte newUid[] = {0x46,0x7E,0xE9,0xA9};
if ( mfrc522.MIFARE_SetUid(newUid, (byte)4, true) ) {
Serial.println( "Wrote new UID to card." );
}
// Halt PICC and re-select it so DumpToSerial doesn't get confused
mfrc522.PICC_HaltA();
if ( ! mfrc522.PICC_IsNewCardPresent() || ! mfrc522.PICC_ReadCardSerial() ) {
return;
}
// Dump the new memory contents
Serial.println( "New UID and contents:" );
mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
}
void setup() {
Serial.begin ( 115200 );
/* RFID */
SPI.begin(); // Initiate SPI bus
mfrc522.PCD_Init(); // Initiate MFRC522
clone();
}
void loop() {
}
When you write
byte newUid[] = {buf};
you are trying to initialise newUid with a single element (there's only one item inside your {}), and that element is buf, which is a char* (or a char[]). That's why you get the error - you are trying to assign an array with one char* to a variable whose elements are bytes.
Without reading your full code in detail, I don't know why you are trying to do this assignment, rather than just use your buf array as it is. But to fix the problem, you probably just want to use
byte* newUid = buf;
I have 8 sensors I read the values from analog ports and I store them in an array. How can I read those values in Visual Basic?
I have a timer that sends '*' to Arduino from VB and then the Arduino returns sensor values. I tried receiving array data in Arduino by sending '&' to make sure that I'm putting the right values in my array.
Arduino code:
uint8_t i;
unsigned char c;
char data[6];
bool rd = false;
String dataString = "";
int sensor;
uint8_t b;
static const uint8_t analog_pins[] = {A0, A1, A2, A3, A4, A5, A6, A7};
int myVals[7];
#include <SPI.h>
#include <SD.h>
const int chipSelect = 4;
void setup() {
Serial.begin(9600);
Serial.println(A0);
while (!Serial) {
;
}
if (!SD.begin(chipSelect)) {
return;
}
File dataFile = SD.open("datalog.txt", FILE_WRITE);
if (dataFile) {
dataFile.println("Gas Sesnor TEST results :");
dataFile.close();
}
}
void loop() {
}
void serialEvent() {
c = Serial.read();
if (c == '*') {
for (b = 0 ; b <= 7 ; b++) {
sensor = analogRead(analog_pins[b]);
myVals[b] = sensor;
Serial.println(sensor);
dataString = String(sensor) + "\n";
File dataFile = SD.open("datalog.txt", FILE_WRITE);
if (dataFile) {
dataFile.println(dataString);
dataFile.close();
}
}
}
if (c == '&') {
for (b = 0; b <= 7; b++) {
Serial.println(myVals[b]);
}
}
}
VB code so far:
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
SerialPort1.WriteLine("*")
receivedData = ReceiveSerialData()
RichTextBox1.Text = receivedData
RichTextBox1.SelectionStart = RichTextBox1.TextLength
RichTextBox1.ScrollToCaret()
Function ReceiveSerialData() As Integer
Try
Dim Incoming As String
Try
Incoming = SerialPort1.ReadExisting()
If Incoming Is Nothing Then
Return 0
Else
Return Incoming
End If
Catch ex As TimeoutException
Return "Error: Serial Port read timed out."
End Try
Catch ex As Exception
End Try
End Function
It keeps returning 0. Please help me.
I am parsing big text files and it's working fine for some time but after few minutes it give me exception (An unhandled exception of type 'System.UnauthorizedAccessException' occurred in System.Core.dll
Additional information: Access to the path is denied.)
I get exception on below mention line.
accessor = MemoryMapped.CreateViewAccessor(offset, length, MemoryMappedFileAccess.Read);
Below is my function
public static void CityStateZipAndZip4(string FilePath,long offset,long length,string spName)
{
try
{
long indexBreak = offset;
string fileName = Path.GetFileName(FilePath);
if (fileName.Contains(".txt"))
fileName = fileName.Replace(".txt", "");
System.IO.FileStream file = new System.IO.FileStream(#FilePath, FileMode.Open,FileAccess.Read, FileShare.Read );
Int64 b = file.Length;
MemoryMappedFile MemoryMapped = MemoryMappedFile.CreateFromFile(file, fileName, b, MemoryMappedFileAccess.Read, null, HandleInheritability.Inheritable, false);
using (MemoryMapped)
{
//long offset = 182; // 256 megabytes
//long length = 364; // 512 megabytes
MemoryMappedViewAccessor accessor = MemoryMapped.CreateViewAccessor(offset, length, MemoryMappedFileAccess.Read);
byte byteValue;
int index = 0;
int count = 0;
StringBuilder message = new StringBuilder();
do
{
if (indexBreak == index)
{
count = count + 1;
accessor.Dispose();
string NewRecord = message.ToString();
offset = offset + indexBreak;
length = length + indexBreak;
if (NewRecord.IndexOf("'") != -1)
{ NewRecord = NewRecord.Replace("'", "''"); }
// string Sql = "insert into " + DBTableName + " (ID, DataString) values( " + count + ",'" + NewRecord + "')";
string Code = "";
if (spName == AppConfig.sp_CityStateZip)
{
Code = NewRecord.Trim().Substring(0, 1);
}
InsertUpdateAndDeleteDB(spName, NewRecord.Trim (), Code);
accessor = MemoryMapped.CreateViewAccessor(offset, length, MemoryMappedFileAccess.Read);
message = new StringBuilder();
index = 0;
//break;
}
byteValue = accessor.ReadByte(index);
if (byteValue != 0)
{
char asciiChar = (char)byteValue;
message.Append(asciiChar);
}
index++;
} while (byteValue != 0);
}
MemoryMapped.Dispose();
}
catch (FileNotFoundException)
{
Console.WriteLine("Memory-mapped file does not exist. Run Process A first.");
}
}
Somewhere deep in resource processing code we have something like this:
try {
// Try loading some strings here.
} catch {
// Oops, could not load strings, try another way.
}
Exception is thrown and handled already, it would never show up in your application. The only way to see it is to attach debugger and observe this message.
As you could see from the code, it has nothing to do with your problem. The real problem here is what debugger shows you something you should not see.
Run the solution without debugging mode and it works fine.
This exception means that your program does not get Read access to the file from Windows.
Have you made sure that this file is not locked when your program tries to read it ?
For example, it could be a file that your own program is currently using.
If not, try to run your program as an Administrator and see if it makes a difference.
im writing a file transfer application to send and receive a large data like 1 GB.. but i think when i read the data from the file and fill it into a byte array it stored on RAM and that would effect on the computer speed .. should i do like :
(loop till end of the file)
{
read 128 MB from the file into byte array
(loop till end of 128)
{
send 1 kb to server
}
byte array = null
}
if that is right ..
which is better to do !! beginSend and beginReceive to send the large file or just loop to send the file
i would be glad if you teach me with some code
thanks in advance :)
Windows will start behaving oddly, if you [begin]Send more than ca. 1MB in one go. This differs between Windows versions, network drivers, shoe size of user and moon phase. Below 1 MB you should be fine.
So, either
(loop till end of the file)
{
read 128 MB from the file into byte array
(loop till end of 128)
{
send 1 MB to server
}
byte array = null
}
or, if it is really a file
SendFile(filename[,...])
even 128mb is not a good way .. its better to read a small buffer .. then send it straight to the other side
check it out.
after you send the fileName and the fileSize to other side
this should be common in (server/client)
FileStream fs;
NetworkStream network;
int packetSize = 1024*8;
Send method
public void Send(string srcPath, string destPath)
{
byte data;
string dest = Path.Combine(destPath, Path.GetFileName(srcPath));
using (fs = new FileStream(srcPath, FileMode.Open, FileAccess.Read))
{
try
{
long fileSize = fs.Length;
long sum = 0;
int count = 0;
data = new byte[packetSize];
while (sum < fileSize)
{
count = fs.Read(data, 0, packetSize);
network.Write(data, 0, count);
sum += count;
}
network.Flush();
}
finally
{
fs.Dispose();
data = null;
}
}
}
Receive method:
public void Receive(string destPath, long fileSize)
{
byte data;
using (fs = new FileStream(destPath, FileMode.Create, FileAccess.Write))
{
try
{
int count = 0;
long sum = 0;
data = new byte[packetSize];
while (sum < fileSize)
{
count = network.Read(data, 0, packetSize);
fs.Write(data, 0, count);
sum += count;
}
}
finally
{
fs.Dispose();
data = null;
}
}
}
I am using Silverlight to interact with a proxy application that I have developed but, without the proxy sending a message to the Silverlight application, it executes the receive completed handler with an empty buffer ('\0's). Is there something I'm doing wrong? It is causing a major memory leak.
this._rawBuffer = new Byte[this.BUFFER_SIZE];
SocketAsyncEventArgs receiveArgs = new SocketAsyncEventArgs();
receiveArgs.SetBuffer(_rawBuffer, 0, _rawBuffer.Length);
receiveArgs.Completed += new EventHandler<SocketAsyncEventArgs>(ReceiveComplete);
this._client.ReceiveAsync(receiveArgs);
if (args.SocketError == SocketError.Success && args.LastOperation == SocketAsyncOperation.Receive)
{
// Read the current bytes from the stream buffer
int bytesRecieved = this._client.ReceiveBufferSize;
// If there are bytes to process else the connection is lost
if (bytesRecieved > 0)
{
try
{
//Find out what we just received
string messagePart = UTF8Encoding.UTF8.GetString(_rawBuffer, 0, _rawBuffer.GetLength(0));
//Take out any trailing empty characters from the message
messagePart = messagePart.Replace('\0'.ToString(), "");
//Concatenate our current message with any leftovers from previous receipts
string fullMessage = _theRest + messagePart;
int seperator;
//While the index of the seperator (LINE_END defined & initiated as private member)
while ((seperator = fullMessage.IndexOf((char)Messages.MessageSeperator.Terminator)) > 0)
{
//Pull out the first message available (up to the seperator index
string message = fullMessage.Substring(0, seperator);
//Queue up our new message
_messageQueue.Enqueue(message);
//Take out our line end character
fullMessage = fullMessage.Remove(0, seperator + 1);
}
//Save whatever was NOT a full message to the private variable used to store the rest
_theRest = fullMessage;
//Empty the queue of messages if there are any
while (this._messageQueue.Count > 0)
{
...
}
}
catch (Exception e)
{
throw e;
}
// Wait for a new message
if (this._isClosing != true)
Receive();
}
}
Thanks in advance.
I assume the second block of code is your ReceiveComplete handler. If so, you should be looking at the SocketAsyncEventArgs.BytesTransferred property to get the count of the bytes received.