Sending integers through serial moniter in arduino - arduino

I am working on doing an Arduino project using a Wifi connection. I was wondering how to send integers through the serial moniter. This is what I have so far:
if(Serial.available()) {
while(Serial.available()) {
char c = Serial.read();
if(c == '\n') {
send_message(client, tx_buffer);
tx_buffer = "";
} else tx_buffer += c;
}
}
This is to send a character through the serial moniter. How would you do it for an integer?

Anything you type in the serial monitor is converted to its ASCII equivalent so typing 3 actually sends '3' == 51. This should work for getting unsigned integers:
unsigned long tx_buffer = 0;
if (Serial.available()) {
while(Serial.available()) {
char c = Serial.read();
if(c == '\r') {
send_message(client, tx_buffer);
tx_buffer = 0;
}
else
tx_buffer = (tx_buffer * 10) + (c - '0');
}
}

Related

Arduino 1 not reading correctly the string from Serial Monitor

I am having a problem with the serial monitor on Arduino Uno.
Basically I want to write some commands on the Serial Monitor, read the string and according to the string do something.
The problem is the following: supposing I type the command 'read 4' in the Serial Monitor, sometimes the string is read correctly, sometimes it is read like: 'ead 4', missing the first character.
I even put a delay between two readings from the Serial Monitor. Does anyone have an explanation?
For completeness I post my code (basically it reads/writes from/to the EEPROM: for example 'read 5' will read the 5 block of EEPROM, 'write 4 5' will write the value 5 to the 4th block of memory).
#define MAX_STRING_LENGTH 14
#include <ctype.h>
#include <EEPROM.h>
//The function initializes the string to spaces
void initString(char* mystr, char strLength);
//The function returns true if it is a read operation, false otherwise
boolean isReadEEPROM(char *myStr, char strLength);
//The function returns true if it is a write operation, false otherwise
boolean isWriteEEPROM(char *myStr, char strLength);
//The function returns the EEPROM address from the string
unsigned int findAddress(char *myStr, char strLength);
char findValue(char *myStr, char strLength);
//Check the address range
boolean isAddressOk(unsigned int address);
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
char pos = 0;
bool newDataFound = false;
char serialStr[MAX_STRING_LENGTH];
unsigned int address = 0;
char val = 0;
while(Serial.available()){
val = Serial.read();
}
val = 0;
initString(&serialStr[0], (char) MAX_STRING_LENGTH);
while(Serial.available() && pos < MAX_STRING_LENGTH){
serialStr[pos] = Serial.read();
pos ++;
newDataFound = true;
delay(200);
}
if (newDataFound){
Serial.print("New Command found: ");
Serial.println(serialStr);
address = 0;
address = findAddress(&serialStr[0], MAX_STRING_LENGTH);
if (isReadEEPROM(&serialStr[0], MAX_STRING_LENGTH) && isAddressOk(address)){
Serial.println("Reading from EEPROM");
Serial.print("Address is ");
Serial.println(address);
val = EEPROM.read(address);
Serial.print("Value is: ");
Serial.println( (uint8_t) val );
Serial.println(" ");
}
else if (isWriteEEPROM(&serialStr[0], MAX_STRING_LENGTH) && isAddressOk(address)){
Serial.println("Writing to EEPROM");
Serial.print("Address is ");
Serial.println(address);
Serial.println(" ");
val = findValue(&serialStr[0], MAX_STRING_LENGTH);
EEPROM.write(address, val);
}
else{
if (!isAddressOk(address)){
Serial.write(address);
Serial.println("Address out of range");
Serial.println("");
}
Serial.println("Not recognized operation\n");
}
delay(2000);
}
}
void initString(char* mystr, char strLength){
for(char ii=0; ii<strLength; ii++){
(*mystr) = ' ';
mystr++;
}
}
//The function returns true if it is a read operation, false otherwise
boolean isReadEEPROM(char *myStr, char strLength){
//The string should contain first the 'read' operation
char expected[] = "read";
int ii =0;
while (ii<4){
if ( *(myStr + ii) != expected[ii]){
return false;
Serial.println("Not a Read Operation\n");
}
ii++;
}
return true;
Serial.println("Read Operation");
}
//The function returns true if it is a write operation, false otherwise
boolean isWriteEEPROM(char *myStr, char strLength){
//The string should contain first the 'read' operation
char expected[] = "write";
int ii =0;
while (ii<5){
if ( *(myStr + ii) != expected[ii]){
return false;
}
ii++;
}
return true;
}
//The function returns the EEPROM address from the string
unsigned int findAddress(char *myStr, char strLength){
unsigned int address;
char tmpStr[strLength];
char strAddress[] = " ";
int ii = 0;
while(ii< strLength){
tmpStr[ii] = *(myStr+ii);
ii++;
}
Serial.print("The address found is: ");
Serial.println(strAddress);
ii= 0;
if (isReadEEPROM(myStr, strLength)){
while (ii<=4){
if (isdigit(*(myStr + 5 + ii))){
strAddress[ii] = *(myStr + 5 + ii);
}
else{
break;
}
ii++;
}
address = atoi(strAddress);
}
else if(isWriteEEPROM(myStr, strLength)){
while (ii<=4){
if (isdigit(*(myStr + 6 + ii))){
strAddress[ii] = *(myStr + 6 + ii);
}
else{
break;
}
ii++;
}
address = atoi(strAddress);
}
else{
address = 0;
//Serial.println("Address not available in function 'findAddress'");
}
return address;
}
//The function returns the value to be written to the EEPROM from the string
char findValue(char *myStr, char strLength){
char val;
char tmpStr[strLength];
char strVal[] = " ";
int ii, idx = 0;
while(ii< strLength){
tmpStr[ii] = *(myStr+ii);
ii++;
}
ii= 0;
// first found the first digits corresponding to the address
while (ii<=4){
if (isdigit(*(myStr + 6 + ii))){
;//strAddress[ii] = *(myStr + 6 + ii);
}
else{
ii++;
break;
}
ii++;
}
// now find the value
while (ii<=4+3){
Serial.println(*(myStr + 6 + ii));
if (isdigit(*(myStr + 6 + ii))){
strVal[idx] = *(myStr + 6 + ii);
}
else{
break;
}
ii++;
idx++;
}
Serial.print("original string: ");
Serial.println(tmpStr);
Serial.print("Value found: ");
Serial.println(strVal);
val = (char)atoi(strVal);
return val;
}
boolean isAddressOk(unsigned int address){
if (address < 1024 && address >= 0){
return true;
}
else{
return false;
}
}
This snippet:
char val=0;
while(Serial.available()){
val = Serial.read();
}
val = 0;
Is just consuming any characters that may be left in the input buffer. You could also do:
while (Serial.avaialble())
Serial.read();
The next while loop does not wait for the entire command. Sometimes, it gets the 'r', and then doesn't get the 'ead...' in time. They will be there the next time loop executes, so it looks like the 'r' is missing. It was just consumed in the previous loop.
Things sent over the USB (from the Serial Monitor window) can have odd delays in them.
To gather up a complete line, you should save characters until a '\n' is received:
for (;;) {
if (Serial.available()) {
char c = Serial.read();
if (c == '\n')
break;
if (pos < MAX_LINE_LENGTH) {
serialStr[pos] = c;
pos ++;
}
newDataFound = true;
}
}
The delay call is totally unnecessary, because the for loop waits until a '\n' character is received (be sure that in the Serial Monitor pull down menu either 'New Line' or 'both NL & CR' is selected). Then you know you've read all the characters in the line.

How to use buffer to read and write using serial port in 8051 MCU

I am using keil c51 compiler. I transmit data from my pc to MCU using serial port it works best.
When I transmit data from my MCU to PC then also it works best.
But when I transmit data to MCU and then store it to buffer character pointer and again from that character pointer buffer I transmit return to PC then it does not work and give garbage values?
My code for both function as below.
#include <REG51.H>
#include "uart.c"
void delay_ms(unsigned int x) // delays x msec (at fosc=11.0592MHz)
{
unsigned char j=0;
while(x-- > 0)
{
for (j=0; j<125; j++){;}
}
}
sbit SW = P3^2;
sbit LED = P3^3;
bit x = 0;
void main ()
{
char *buf;
int len=0;
int len1 = 0;
uart_init();
while(1){
if(RI == 1){
UART_RxString(buf,&len);
buf -= (len-1) ;
x = 1;
}
if(x == 1 && SW == 0){
UART_TxString(buf,&len1);
x = 0;
}
}
}
And below are the functions.
1.
void UART_TxString(char *string_ptr, int *l)
{
int count = 0;
while(*string_ptr){
UART_TxChar(*string_ptr++);
count++;
}
*l = count;
}
void UART_RxString(char *string_ptr, int *l)
{
char ch;
int count = 0;
while(1)
{
ch=UART_RxChar(); //Reaceive a char
//UART_TxChar(ch); //Echo back the received char
count++;
if((ch=='\r') || (ch=='\n')) //read till enter key is pressed
{ //once enter key is pressed
*string_ptr=0; //null terminate the string
break; //and break the loop
}
*string_ptr=ch; //copy the char into string.
string_ptr++; //and increment the pointer
}
*l = count;
}

ASCII reading with arduino

This is my first post, I know this theme could be very simple or obvious but I can't figure out how to solve it.
I have a capacitance meter from jyetech wiuch claims to have a 8-N-1 serial output, here is the link to the manual. I just want to read the output with my Arduino Uno, can anyone help me? Here is the code I have done, I'm getting some real data but also some strange characters.
#include <stdio.h>
void setup() {
Serial.begin(38400);
Serial.println("OK");
}
char command[1024];
char commandBuffer[128];
int commandBufferSize = 0;
void readCommandBuffer(int bytesToRead) {
int i = 0;
char c = 0;
while (i < 128 && (i < bytesToRead || bytesToRead <= 0)) {
while (!Serial.available())
;
c = Serial.read();
if (c == '\r' || c == '\n') {
break;
}
commandBuffer[i] = c;
i++;
}
commandBufferSize = i;
}
void readCommand() {
command[0] = '\0';
readCommandBuffer(0);
if (strncmp(commandBuffer, "RCV", 3) == 0) {
commandBuffer[commandBufferSize] = '\0';
int expectedSize = atoi(commandBuffer + 4);
if (expectedSize <= 0 || expectedSize > 1024) {
return;
}
Serial.println("RDY");
int bytesRead = 0;
while (bytesRead < expectedSize) {
readCommandBuffer(expectedSize - bytesRead);
memcpy(command + bytesRead, commandBuffer, commandBufferSize);
bytesRead += commandBufferSize;
Serial.print("ACK ");
Serial.println(commandBufferSize);
}
command[bytesRead] = '\0';
} else {
memcpy(command, commandBuffer, commandBufferSize);
command[commandBufferSize] = '\0';
}
}
void loop() {
if (Serial.available()) {
readCommand();
// "command" now contains the full command
Serial.println(command);
}}
You have to use two serial ports, one to talk to the PC (the usual Serial object), and the other to talk to the instrument.
If you have an Arduino UNO, which has only one hardware serial port, you have to use the software serial library. Mega boards have instead 4 hardware serial ports, which are available through the bulit-in objects Serial1, Serial2, etc.
BTW, just noticed a very similar question was asked awhile ago:
Serial Data communication Arduino

Arduino : Check byte array for chars one at a time

I communicate with Arduino via Serial using a program that sends a series of bytes.
In order for the Arduino to realize it is receiving a message rather than junk, I have tagged the start of my byte array with the chars 'S' 'T' 'A' 'R' 'T'. After this will eventually follow a series of bytes that will be assigned to internal variables (not yet implemented).
The Arduino must read each byte sequentially and compare it to the byte array and if all are present in the correct order it will continue with the next part of the program, otherwise it will should discard current byte and wait for more bytes to arrive.
I am trying to implement it in the most efficient and readable way rather than using a series of nested if statements.
So far I have got:
byte inByte = 0;
byte handShake[] = {'S','T','A','R','T'};
void setup() {
Serial.begin(9600);
}
void loop()
{
while (Serial.available())
{
for (int x =0; x < sizeof(handShake) ; x++)
{
inByte = Serial.read();
Serial.println(x);
if (inByte == handShake[x])
{
if (x == (sizeof(handShake)-1)) {setArduino();}
}
else break;
}
}
}
void setArduino () {
Serial.println("Ready To Set Parameters");
}
This however doesn't seem to get past the second byte and I'm not sure why.
Worked it out :
Here is the answer:
byte inByte = 0;
char handShake[] = {'S','T','A','R','T'};
void setup() {
Serial.begin(9600);
}
void loop()
{
while (Serial.available())
{
for (int x =0; x < sizeof(handShake) ; x++)
{
inByte = Serial.read();
Serial.println(x);
if (inByte == handShake[x])
{
if (x == (sizeof(handShake)-1)) {setArduino();}
while(!Serial.available()) {delay(1);}
}
else {break;}
}
}
}
void setArduino () {
Serial.println("Ready To Set Parameters");
}
This may not be the most efficient way perhaps, but I can't see a problem with it currently.
Better answer : This allows the rest of the loop to iterate while waiting for the message to finish and if the full handshake message isn't received the counter will reset.
byte inByte = 0;
char handShake[] = {'S','T','A','R','T'};
int messageIndex = 0;
void setup() {
Serial.begin(9600);
}
void loop()
{
while (Serial.available())
{
inByte = Serial.read();
Serial.println(messageIndex);
if (inByte == handShake[messageIndex])
{
messageIndex++;
if (messageIndex == sizeof(handShake)) {messageIndex = 0; setArduino();}
}
else {messageIndex=0;}
}
// Other code while waiting for message to finish
Serial.println("tick");
}
void setArduino () {
Serial.println("Ready To Set Parameters");
}
You could try to calculate your message. CRC is old and good solution. I use it and it works perfect for me. I am not sure what kind of device are you communicating with.
//define
const uint32_t Polynomial = 0xEDB88320;
const uint16_t NumBytes = 256;
uint8_t data[NumBytes];
/// compute CRC32
uint32_t crc32_bitwise(const void* data, uint16_t length, uint32_t previousCrc32 = 0)
{
uint32_t crc = ~previousCrc32; // same as previousCrc32 ^ 0xFFFFFFFF
uint8_t* current = (uint8_t*) data;
while (length--)
{
crc ^= *current++;
for (uint8_t j = 0; j < 8; j++)
{
uint8_t lowestBit = crc & 1;
crc >>= 1;
if (lowestBit)
crc ^= Polynomial;
}
}
return ~crc; // same as crc ^ 0xFFFFFFFF
}
void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
}
when you need to calculate CRC
uint32_t crc = crc32_bitwise(data_bytes, sizeof(data_bytes));
data_bytes is byte array.
Then you can get all settings or message in byte data[x] and calculate CRC. Then you can add CRC to the message and send message byte data[x+sizeof(CRC)]
P.S. Use byte instead of int. For ex. for(byte x =0; x<sizeof(handShake); x++)

Arduino Sketch - Reading Serial Bytes

I have the following code on my Arduino that constantly checks for a serial command that's sent over TCP using a Wifly library.
What the following code does is split a string like the following when sent over serial:
{power,tv}
It sets these properties accordingly:
char command[32];
char value[32];
It then executes certain methods using sendCommand(command, value); based on the properties set in the loop below.
Keep in mind this works just fine using the Wifly library.
void loop() {
Client client = server.available();
if (client) {
boolean start_data = false;
boolean next = false;
char command[32];
char value[32];
int index = 0;
while (client.connected()) {
if (client.available()) {
char c = client.read();
Serial.print(c);
if (c == '}') {
break;
}
if(start_data == true) {
if(c != ',') {
if(next)
value[index] = c;
else
command[index] = c;
index++;
} else {
next = true;
command[index] = '\0';
index = 0;
}
}
if (c == '{') {
start_data = true;
}
}
}
value[index] = '\0';
client.flush();
client.stop();
sendCommand(command,value);
}
}
Instead of using WiFi I've purchased some Xbee modules. They basically allow you to send serial bytes as well. The only problem is that I'm not quite sure how to handle the looping considering there's no while(client.connected()) anymore. Instead of that I've used while(Serial.available()) thinking that will work, but it doesn't set the value property for some reason.
I get command but I don't get value.
Also I'm not sure whether the loop above is the best way of doing what I'm after, all I know is that it works just fine the way it is. :)
Here is my new loop, which only returns command and not value for some reason:
void loop() {
// if there are bytes waiting on the serial port
if (Serial.available()) {
boolean start_data = false;
boolean next = false;
char command[32];
char value[32];
int index = 0;
while (Serial.available()) {
char c = Serial.read();
Serial.print(c);
if (c == '}') {
break;
}
if(start_data == true) {
if(c != ',') {
if(next)
value[index] = c;
else
command[index] = c;
index++;
} else {
next = true;
command[index] = '\0';
index = 0;
}
}
if (c == '{') {
start_data = true;
}
}
value[index] = '\0';
sendCommand(command,value);
}
}
If the following works with the new loop, I'll be very happy!
void sendCommand(char *command, char *value) {
// do something wonderful with command and value!
}
Got it working by using the following code:
#define SOP '{'
#define EOP '}'
bool started = false;
bool ended = false;
char inData[80];
byte index;
void setup()
{
Serial.begin(9600);
// Other stuff...
}
void loop()
{
// Read all serial data available, as fast as possible
while(Serial.available() > 0)
{
char inChar = Serial.read();
if(inChar == SOP)
{
index = 0;
inData[index] = '\0';
started = true;
ended = false;
}
else if(inChar == EOP)
{
ended = true;
break;
}
else
{
if(index < 79)
{
inData[index] = inChar;
index++;
inData[index] = '\0';
}
}
}
// We are here either because all pending serial
// data has been read OR because an end of
// packet marker arrived. Which is it?
if(started && ended)
{
// The end of packet marker arrived. Process the packet
char *cmd = strtok(inData, ",");
if(cmd)
{
char *val = strtok(NULL, ",");
if(val)
{
sendCommand(cmd, val);
}
}
// Reset for the next packet
started = false;
ended = false;
index = 0;
inData[index] = '\0';
}
}
I would change the structure similar to:
while( c != '}') {
if (Serial.available()) {
.
.
.
}
}
Serial characters are received significantly slower then the loop.

Resources