Sending decimals using radio.write(); with Arduino - c

I'm adapting a sketch I found to send sensor data over a wifi chip (Nrf2401), and although I get the message through, the value I send contains decimals (e.g. 24.59), but the received message will only be 24.
I'm sure there's something wrong on the transmitter part of the code, but I can't see what.
Here's my code:
#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>
#include <OneWire.h>
#include <DallasTemperature.h>
OneWire oneWire(4);
DallasTemperature sensors(&oneWire);
// ce,csn pins
RF24 radio(8,7);
unsigned char data[3] = {
0};
unsigned long count=0;
void setup(void)
{
sensors.begin();
Serial.begin(57600);
Serial.println("**************V1 Send Sensor Data***********");
radio.begin();
radio.setPALevel(RF24_PA_LOW);
radio.setChannel(0x4c);
// open pipe for writing
radio.openWritingPipe(0xF0F0F0F0E1LL);
radio.enableDynamicPayloads();
radio.setAutoAck(true);
radio.powerUp();
Serial.println("...Sending");
}
void loop(void)
{
sensors.requestTemperatures();
float currentTemp;
currentTemp = sensors.getTempCByIndex(0);
//assign 'T' to represent a Temperature reading
data[0] = 'T';
data[1] = currentTemp;
count++;
// print and increment the counter
radio.write(data, sizeof(float)+1);
Serial.print("Temperature sent: ");
Serial.println(currentTemp);
// pause a second
delay(500);
}
In this example, when I print currentTemp, it will display the decimals, but if I print data[1], it won't.
What am I missing?

You are assigning data [1] = currentTemp. Current temp is a float, not a character so this won't work. Decimals are lost because the float will be cast to a char in the assignment. Make data into a larger buffer and use sprintf to print currentTemp if you want to use it as a string. Really you should be writing just currentTemp to the radio and formatting on the other end, which will make the operation faster and require less bandwith to transmit (not to mention that transmitting and formatting are different concerns and should be separated, not coupled, when possible).

Related

Why my arduino serial to LCD gets stuck after 26 loop?

I get a float from raspberry pi (via struct module) and my sketch only shows the data on an LCD screen.
After 26 corrects loop, on the 27th, the Arduino crashes.
Can you tell me what's wrong with the 27th?
Changing delay from 20ms to 1s: NOK
Put the byte pointer out of the function: NOK
float f;
void getFloat(){
byte *fdata = (byte *) &f;
while(Serial.available() <= 4){}
Serial.readBytes(fdata,4);
}
void loop() {
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 0);
lcd.print("Ready to receive");
getFloat();
AZ=f;
getFloat();
AL=f;
lcd.setCursor(0, 0);
lcd.print("Moving ");
lcd.setCursor(0, 1);
// print the number of seconds since reset:
lcd.print("AZ");
lcd.print(String(AZ));
lcd.setCursor(7, 1);
lcd.print("; AL");
lcd.print(String(AL));
delay(1000);
Serial.println("ok");
}
At the 27th, the arduino no longer acknoledge the data and the LCD shows :
==ving
AZy ; AL0.00=
=== Resolution ===
Before, I have to send twice the floats via the next code to get the last if not, I get the previous data on my arduino but i think the limitation comes from there :
def sendFloatToArduino(self,data):
self.serial.write(struct.pack('<f', data))
self.serial.flush()
def pointer(self,AZ,AL):
#send the data
print("AZ : "+str(AZ)+" ; AL : "+str(AL))
self.sendFloatToArduino(AZ)
self.sendFloatToArduino(AL)
self.sendFloatToArduino(AZ)
self.sendFloatToArduino(AL)
#wait for ack
while (self.serialArduino.in_waiting==0):
pass
print(self.serialArduino.readline())
After deleting the double sending, everything is fine.
Thanks for your answers.
The problem is not about the parsing as you said but with the LCD display.
I've tried converting floats to array and geting only 16 characters:
char str[16];
AZ=getFloat();
AL=getFloat();
char buffer1[20];
char buffer2[20];
dtostrf(AZ,7,5,buffer1);
dtostrf(AL,7,5,buffer2);
for (int i=0;i<8;i++){
if (i>1){
str[i]=buffer1[i-2];
str[i+8]=buffer2[i-2];
}
}
Serial.println(str);
But I get this on serial output : AZ358.54AL48.544\x12.BBHE\xb3CGm=\r\n => fixed with \0
I think the problem is elswhere : I have to send twice the floats via the next code to get the last if not, I get the previous data on my arduino but i think the limitation comes from there :
def sendFloatToArduino(self,data):
self.serial.write(struct.pack('<f', data))
self.serial.flush()
def pointer(self,AZ,AL):
#send the data
print("AZ : "+str(AZ)+" ; AL : "+str(AL))
self.sendFloatToArduino(AZ)
self.sendFloatToArduino(AL)
self.sendFloatToArduino(AZ)
self.sendFloatToArduino(AL)
#wait for ack
while (self.serialArduino.in_waiting==0):
pass
print(self.serialArduino.readline())
I can't figure out the problem, but you can try the following code. It's stronger I think.
float getFloat()
{
float res;
while (Serial.available() < sizeof(res))
;
Serial.readBytes((char*)&res, sizeof(res));
return res;
}
void loop()
{
// ...
AZ = getFloat();
AL = getFloat();
// ...
}

AVR gcc, weird array behaviour

it's the first time I see something like this. I'm starting to suspect it's a hardware fault.
whenever I try to send the contents of array "test" and that array is larger than 4 elements or I initialize all elements in the declaration it contains 0xff instead of values I try to initialise with.
this works fine. when I read values from the array in while(sending them to the lcd and uart) both readouts are consistent with test values:
uint8_t i=0;
uint8_t test[4] = {1,2,3,4};
while(i<5){
GLCD_WriteData(test[i]);
USART_Transmit(test[i]);
i++;
}
this doesn't, it returns 0xff instead of test[i] value:
uint8_t i=0;
uint8_t test[5] = {1,2,3,4,5};
while(i<5){
GLCD_WriteData(test[i]);
USART_Transmit(test[i]);
i++;
}
but this works! it returns proper values
uint8_t i=0;
uint8_t test[6] = {1,2,3,4,5};
while(i<5){
GLCD_WriteData(test[i]);
USART_Transmit(test[i]);
i++;
}
this also works:
uint8_t i=0;
uint8_t test[5];
test[0]=1;
test[1]=2;
test[2]=3;
test[3]=4;
test[4]=5;
while(i<5){
GLCD_WriteData(test[i]);
USART_Transmit(test[i]);
i++;
}
it works fine when compiled on linux
I swapped out an mcu for a different one and it works the way it should. must be an hardware problem
In first example you are going out of bounds of array test[4]. You are running while 5 times, when array has only 4 items length.
I think your problem is that you're overloading the USART. I assume that GLCD_WriteData() is VERY quick, and that USART_Transmit() buffers the character for transmission and then quickly returns. I don't know your hardware, so I can't tell - but a four-character buffer for a USART sounds reasonable.
Your five-character examples don't work because the actual character that you're trying to transmit is lost - so it puts an 0xFF in instead. You need to check the state of the USART buffer and wait for it to show that space is available (note NOT empty - that'd be inefficient!).
In the 8250 and 16450 UART chips there are two status bits:
TSRE says that the Transmit Shift Register is Empty;
THRE says that the Transmit Holding Register is Empty.
THRE can be set even when TSRE isn't - it's busy. I'd test TSRE and not send the next character until there's room - or set up a buffer and an interrupt handler.
If it's not the I/O hardware, then the only other thing that I can think of is the compiler is producing incorrect code. What is the exact declaration of USART_Transmit()? Does it expect a uint8_t? Or something else, like an int (for some reason)?
If it's something else, like int, please try the following code:
while(i<5){
int c = test[i]; // Whatever USART_Transmit wants
GLCD_WriteData(test[i]);
USART_Transmit(c);
i++;
} // while
If that always works, then you've got a compiler problem, not a hardware problem.
EDIT: Code for USART_Transmit() provided:
void USART_Transmit( uint8_t data ) {
//Wait for empty transmit buffer
while( !( UCSR0A & (1<<UDRE0)) );
//Put data into buffer, sends the data
UDR0 = data;
}
You've got something better than JTAG - you've got an LCD display! Although I don't know how many characters it has, or how long it takes to transmit a character...
You could try something like:
char Hex(uint8_t nibble) {
return nibble<10 ?
'0'+nibble :
'A'+nibble-10;
} // Hex
...
void Send(uint8_t c) {
uint8_t s;
UDR0 = c; // Send character NOW: don't wait!
do {
s = UCSR0A; // Get current USART state
//s = UCSR0A & (1<<UDRE0); // Or this: isolate ready bit...
GLCD_WriteData('x');
GLCD_WriteData(Hex(s >> 4)); // Write state-hi hex
GLCD_WriteData(Hex(s & 0xF)); // Write state-lo hex
} while (!(s & (1<<UDRE0))); // Until is actually ready
} // Send(c)
...
Send('A');
Send('B');
Send('C');
Assuming that UDRE0 is 3, then that code will result in a sequence like x00x00x00x00x00x08x00x00x00x00x08x00x00x00x08 if it is working. If it produces x08x08x08 then you've got a stuck UCSR0A bit, and it's hardware.
Old question, but giving my feedback since this is the first place I got sent while searching solution for same issue, getting even exact same results with the code samples in original question.
For me it was a bad Makefile that caused some sections to be left out by avr-objcopy as far as I know.
For example in my case, the original parameters for building my sample hex that were causing this issue:
${OBJCOPY} -j .text -O ihex led.elf led.hex
What worked a bit better:
${OBJCOPY} -O ihex -R .eeprom led.elf led.hex

Reading serial port faster

I have a computer software that sends RGB color codes to Arduino using USB. It works fine when they are sent slowly but when tens of them are sent every second it freaks out. What I think happens is that the Arduino serial buffer fills out so quickly that the processor can't handle it the way I'm reading it.
#define INPUT_SIZE 11
void loop() {
if(Serial.available()) {
char input[INPUT_SIZE + 1];
byte size = Serial.readBytes(input, INPUT_SIZE);
input[size] = 0;
int channelNumber = 0;
char* channel = strtok(input, " ");
while(channel != 0) {
color[channelNumber] = atoi(channel);
channel = strtok(0, " ");
channelNumber++;
}
setColor(color);
}
}
For example the computer might send 255 0 123 where the numbers are separated by space. This works fine when the sending interval is slow enough or the buffer is always filled with only one color code, for example 255 255 255 which is 11 bytes (INPUT_SIZE). However if a color code is not 11 bytes long and a second code is sent immediately, the code still reads 11 bytes from the serial buffer and starts combining the colors and messes them up. How do I avoid this but keep it as efficient as possible?
It is not a matter of reading the serial port faster, it is a matter of not reading a fixed block of 11 characters when the input data has variable length.
You are telling it to read until 11 characters are received or the timeout occurs, but if the first group is fewer than 11 characters, and a second group follows immediately there will be no timeout, and you will partially read the second group. You seem to understand that, so I am not sure how you conclude that "reading faster" will help.
Using your existing data encoding of ASCII decimal space delimited triplets, one solution would be to read the input one character at a time until the entire triplet were read, however you could more simply use the Arduino ReadBytesUntil() function:
#define INPUT_SIZE 3
void loop()
{
if (Serial.available())
{
char rgb_str[3][INPUT_SIZE+1] = {{0},{0},{0}};
Serial.readBytesUntil( " ", rgb_str[0], INPUT_SIZE );
Serial.readBytesUntil( " ", rgb_str[1], INPUT_SIZE );
Serial.readBytesUntil( " ", rgb_str[2], INPUT_SIZE );
for( int channelNumber = 0; channelNumber < 3; channelNumber++)
{
color[channelNumber] = atoi(channel);
}
setColor(color);
}
}
Note that this solution does not require the somewhat heavyweight strtok() processing since the Stream class has done the delimiting work for you.
However there is a simpler and even more efficient solution. In your solution you are sending ASCII decimal strings then requiring the Arduino to spend CPU cycles needlessly extracting the fields and converting to integer values, when you could simply send the byte values directly - leaving if necessary the vastly more powerful PC to do any necessary processing to pack the data thus. Then the code might be simply:
void loop()
{
if( Serial.available() )
{
for( int channelNumber = 0; channelNumber < 3; channelNumber++)
{
color[channelNumber] = Serial.Read() ;
}
setColor(color);
}
}
Note that I have not tested any of above code, and the Arduino documentation is lacking in some cases with respect to descriptions of return values for example. You may need to tweak the code somewhat.
Neither of the above solve the synchronisation problem - i.e. when the colour values are streaming, how do you know which is the start of an RGB triplet? You have to rely on getting the first field value and maintaining count and sync thereafter - which is fine until perhaps the Arduino is started after data stream starts, or is reset, or the PC process is terminated and restarted asynchronously. However that was a problem too with your original implementation, so perhaps a problem to be dealt with elsewhere.
First of all, I agree with #Thomas Padron-McCarthy. Sending character string instead of a byte array(11 bytes instead of 3 bytes, and the parsing process) is wouldsimply be waste of resources. On the other hand, the approach you should follow depends on your sender:
Is it periodic or not
Is is fixed size or not
If it's periodic you can check in the time period of the messages. If not, you need to check the messages before the buffer is full.
If you think printable encoding is not suitable for you somehow; In any case i would add an checksum to the message. Let's say you have fixed size message structure:
typedef struct MyMessage
{
// unsigned char id; // id of a message maybe?
unsigned char colors[3]; // or unsigned char r,g,b; //maybe
unsigned char checksum; // more than one byte could be a more powerful checksum
};
unsigned char calcCheckSum(struct MyMessage msg)
{
//...
}
unsigned int validateCheckSum(struct MyMessage msg)
{
//...
if(valid)
return 1;
else
return 0;
}
Now, you should check every 4 byte (the size of MyMessage) in a sliding window fashion if it is valid or not:
void findMessages( )
{
struct MyMessage* msg;
byte size = Serial.readBytes(input, INPUT_SIZE);
byte msgSize = sizeof(struct MyMessage);
for(int i = 0; i+msgSize <= size; i++)
{
msg = (struct MyMessage*) input[i];
if(validateCheckSum(msg))
{// found a message
processMessage(msg);
}
else
{
//discard this byte, it's a part of a corrupted msg (you are too late to process this one maybe)
}
}
}
If It's not a fixed size, it gets complicated. But i'm guessing you don't need to hear that for this case.
EDIT (2)
I've striked out this edit upon comments.
One last thing, i would use a circular buffer. First add the received bytes into the buffer, then check the bytes in that buffer.
EDIT (3)
I gave thought on comments. I see the point of printable encoded messages. I guess my problem is working in a military company. We don't have printable encoded "fire" arguments here :) There are a lot of messages come and go all the time and decoding/encoding printable encoded messages would be waste of time. Also we use hardwares which usually has very small messages with bitfields. I accept that it could be more easy to examine/understand a printable message.
Hope it helps,
Gokhan.
If faster is really what you want....this is little far fetched.
The fastest way I can think of to meet your needs and provide synchronization is by sending a byte for each color and changing the parity bit in a defined way assuming you can read the parity and bytes value of the character with wrong parity.
You will have to deal with the changing parity and most of the characters will not be human readable, but it's gotta be one of the fastest ways to send three bytes of data.

Arduino: string to multiple variables

I'm trying to send the data from two sensors through 433MHz radio communication. I have succeeded in sending and receiving the string(array of char) "number1,number2".
Now I'm trying to store both numbers in separate int variables (the values are over 256).
I've tried with almost everything (sscanf and atoi mainly), but it does not seem to work.
To A0 and A1 I have connected two potentiometers, whose values I want to store in valorX and valorY in the receiver arduino.
What do you suggest?
I cannot assure I used correctly sscanf and atoi.
Transmitter code:
#include <VirtualWire.h>
int xvalue;
int yvalue;
void setup() {
Serial.begin(9600);
vw_set_ptt_inverted(true); //
vw_set_tx_pin(12);
vw_setup(4000);// speed of data transfer Kbps
}
void loop() {
xvalue=analogRead(A0);
yvalue=analogRead(A1);
int envioX = map(xvalue, 0, 1023, 001, 1000); //I prefer to not send 0
int envioY = map(yvalue, 0, 1023, 001, 1000);
//Mando los datos del joystic
char envioXY[]="";
sprintf(envioXY,"%d,%d",envioX,envioY);
EnviarDatos(envioXY);
delay(1000);
}
void EnviarDatos(char datos[]){
vw_send((uint8_t *)datos, strlen(datos)); //vw_send(message, length)
vw_wait_tx(); // Wait until the whole message is gone
}
Receiver code:
#include <VirtualWire.h>
char recibo[8]="";
int valorX;
int valorY;
void setup(){
vw_set_ptt_inverted(true); // Required for DR3100
vw_set_rx_pin(12);
vw_setup(4000); // Bits per sec
vw_rx_start(); // Start the receiver PLL running
Serial.begin(9600);
Serial.println("setup");
}
void loop(){
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;
if (vw_get_message(buf, &buflen)){ //check to see if anything has been received
for(int i=0;i<buflen;i++){
recibo[i]=char(buf[i]);
Serial.print(recibo[i]);
}
recibo[buflen]=NULL;
//String str(recibo);
//What here to get both int??
}
}
What do you suggest?
I cannot assure I used correctly sscanf and atoi.
So the main question is how to convert "number1,number2" to int1=number1 and int2=number2.
Thanks and cheers
Gabriel
Transmitter code:
You must declare storage for the sprintf to use. You have only declared a 1-byte array which contains a NUL (0 byte) as the first and only element [0]:
char envioXY[]="";
Change it to this, which declares a character array with 24 elements:
char envioXY[ 24 ];
Although uninitialized, sprintf will set the array elements as it formats your 2 integers.
Receiver code:
After recibo[buflen] = NULL;, you can parse it with this:
sscanf( recibo, "%d,%d", &valorX, &valorY );
The format string matches the sprintf format, and the address of the two integers is passed in, not just the two integers.

Arduino conversions in C

void digitalClockDisplay(){
// digital clock display of the time
Serial.print(hour());
printDigits(minute());
Serial.println();
}
void printDigits(int digits){
// utility function for digital clock display: prints preceding colon and leading 0
Serial.print(":");
if(digits < 10)
Serial.print('0');
Serial.print(digits);
}
//I tried something like this
//void time(){
//char* hr = (char*)hour();
//Serial.println(hr);
//}
//But when I print it it gives a whole bunch of jibberish
Here are the two functions I'm using what I'm trying to do is make a function like the digitalClockDisplay function but one that returns the hour:minute as a char* once I have that I want to be able to compare that to another char*
hour() seems to be returning a int, so
char* hr = (char*)hour();
Serial.println(hr);
casts a int to a pointer and then sends the bytes at that (meaningless) address to Serial.
You probably want something like:
char hr[8];
snprintf(hr,8,"%i:%02i",hour(),minute());
Serial.println(hr);

Resources