I have got a task of sending hexadecimal data to my COMPORT in linux. I have written this simple C code, but it sends only a decimal number. Can anyone help me in sending an hexadecimal bit.
Here is the code I have written
#include <stdio.h> /* Standard input/output definitions */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
int number,n;
void main(void){
open_port();
}
int open_port(void)
{
int fd; /* File descriptor for the port */
fd = open("/dev/ttyACM0", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
{
perror("open_port: Unable to open /dev/ttyACM0 - ");
}
else{
printf("Port Opened successfully\n");
number = 1;
while(number!=55){
scanf("%d",&number);
n = write(fd, "ATZ\r", number);
if (n < 0)
fputs("write() of 4 bytes failed!\n", stderr);
}
}
return (fd);
}
Please help
Thanks in advance :) :)
write is defined as:
ssize_t write(int fd, const void *buf, size_t count);
That is, it sends count bytes to fd from buf. In your case, the data is always the string "AZTR\r", plus undefined data after that (if count is > 5). Your program sends neither hexadecimal nor decimal data.
Do you want to send binary data or a string of hexadecimal characters?
For option one, you can use: write(fd, somebuffer, len);, where some buffer is a pointer to any set of bytes (including ints, etc).
For option two, first convert your data to a hexadecimal string using sprintf with %02X as the format string, then proceed to write that data to the port.
There are several problems with the code:
The text read from the console is interpreted as decimal ("%d"); if you want it to be interpreted as hexadecimal, use "%x".
The write() is pathological. The third argument is the number of bytes to write, not the value. It should be either
n = write (fd, "ATZ\r", 4); // there are 4 bytes to write to init the modem
or
char buf[10];
n = sprintf (buf, "%x", number); // convert to hex
n = write (fd, buf, n); // send hex number out port
This function will take a hex string, and convert it to binary, which is what you want to actually send. the hex representation is for humans to be able to understand what is being sent, but whatever device you are communicating with, will probably need the actual binary values.
// Converts a hex representation to binary using strtol()
unsigned char *unhex(char *src) {
unsigned char *out = malloc(strlen(src)/2);
char buf[3] = {0};
unsigned char *dst = out;
while (*src) {
buf[0] = src[0];
buf[1] = src[1];
*dst = strtol(buf, 0, 16);
dst++; src += 2;
}
return out;
}
Related
I'm currently trying to send raw binary data in the format of decimal to an external device over serial. I currently have the data in a buffer array but would like it in a structure like this:
struct packetData{
uint8_t sync1;
uint8_t sync2;
uint16_t messageId;
uint16_t dataWordCount;
uint16_t flags;
uint16_t checksum;
};
I'm also using 9600 baud, and have all the termios settings set using cfmakeraw and I'm currently writing using:
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
int flags = O_RDWR | O_NOCTTY | O_NDELAY;
fd = open(device, flags);
uint16_t buf_tx[BUFFER_SIZE] = {255,129,191,0,2057,0};
if(fd == -1){
printf("\n Failed to open port! ");
return -1;
}
tcgetattr(fd, &tty); //Get the current attributes of the Serial port
cfmakeraw(&tty);
cfsetispeed(&tty, B9600); //Set read speed as 9600 baud
cfsetospeed(&tty, B9600); //Set write speed as 9600 baud
if((tcsetattr(fd, TCSANOW, &tty)) != 0){
printf("Error! Can't set attributes.\n");
return -1;
}
else{
printf("Connection successful! \n");
}
while(x < 1000){
memset(buf_tx, 0, sizeof(buf_tx));
tcflush(fd, TCOFLUSH);
if(y < 5){
if(write(fd, buf_tx, 5) == -1){
printf("\n");
printf("Error>>: %s\n",strerror(errno));
y++;
}
}
tcflush(fd, TCIOFLUSH);
usleep(1000);
x++;
}
This code isnt the full code, just the setup/write parts so no need to worry about its syntax. if possible it would be nice not to have that buffer array and just use the struct directly, but I'll take what I can get.
It seems you have the serial port opening more or less in hand. I prefer to set the termios member components explicitly myself, but cfmakeraw() is perfectly fine too.
What you should consider, is having a separate function to send one or more of those structures at a time. For example,
int write_all(const int fd, const void *buf, const size_t len)
{
const char *data = buf;
size_t written = 0;
ssize_t n;
while (written < len) {
n = write(fd, data + written, len - written);
if (n > 0) {
written += n;
} else
if (n != -1) {
/* C library bug, should never occur */
errno = EIO;
return -1;
} else {
/* Error; n == -1, so errno is already set. */
return -1;
}
}
/* Success. */
return 0;
}
The function will return 0 if all data was successfully written, and -1 with errno set if an error occurs.
To send a struct packetData pkt; just use write_all(fd, &pkt, sizeof pkt).
To send a full array struct packetData pkts[5]; use write_all(fd, pkts, sizeof pkts).
To send n packets starting at pkts[i], use write_all(fd, pkts + i, n * sizeof pkts[0]).
However, you do not want to use tcflush(). It does not do what you think it does; it actually just discards data.
Instead, to ensure that the data you have written has been transmitted, you need to use tcdrain(fd).
I recommend against adding tcdrain(fd) at the end of write_all() function, because it blocks, pauses the program, until the data has been transmitted. This means that you should only use tcdrain() before you do something that requires the other end has received the transmission; for example before trying to read the response.
However, if this is a query-response interface, and you do intend to also read from the serial device, you should set tty.c_cc[VMIN] and tty.c_cc[VTIME] to reflect how you intend to use the interface. I prefer asynchronous full-duplex operation, but that requires select()/poll() handling. For half-duplex, with these exact structures only, you can use tty.c_cc[VMIN] = sizeof (struct packetData) with say tty.c_cc[VTIME] = 30, which causes read() to try and wait until a full structure is available, but at most 30 deciseconds (3.0 seconds). Something like tty.c_cc[VMIN] = 1; tty.c_cc[VTIME] = 1; is more common; that causes read() to return a short count (even 0!) if there is no additional data received within a decisecond (0.1 seconds). Then, the receive function could be along the following lines:
int read_all(const int fd, void *buf, const size_t len)
{
char *const ptr = buf;
size_t have = 0;
ssize_t n;
/* This function is to be used with half-duplex query-response protocol,
so make sure we have transmitted everything before trying to
receive a response. Also assumes c_cc[VTIME] is properly set for
both the first byte of the response, and interbyte response interval
in deciseconds. */
tcdrain(fd);
while (have < len) {
n = read(fd, ptr + have, len - have);
if (n > 0) {
have += n;
} else
if (n == 0) {
/* Timeout or disconnect */
errno = ETIMEDOUT;
return -1;
} else
if (n != -1) {
/* C library bug, should never occur */
errno = EIO;
return -1;
} else {
/* Read error; errno set by read(). */
return -1;
}
}
/* Success; no errors. */
return 0;
}
If this returns -1 with errno == ETIMEDOUT, the other side took too long to answer. There may be remainder of the late response in the buffer, which you can discard with tcflush(TCIFLUSH) (or with tcflush(TCIOFLUSH), which also discards any written data not yet transmitted). Synchronization in this case is a bit difficult, because the above read_all() function doesn't return how many bytes it received (and therefore how many bytes to discard of a partial structure).
Sometimes the interface used always returns the number of bytes, but also sets errno (to 0 if no error occurred, and a nonzero error constant otherwise). That would be better for a query-response interface read and write functions, but many programmers find this use case "odd", even though it is perfectly okay by POSIX.1 standard (which is the relevant standard here).
I am using this source code to read from the serial port of a linux machine. I am able to read from the port, but all of the values are in ascii gibberish ( i am reading the input from an xbox controller). I know I am sending it correctly, i.e. i can see on my side I am sending -128 - 127 as a char, but when I am converting it on my linux machine using atoi its returning 0, or when I try to cast the data to int it returns -48 , equivalent to 0 in ascii.
Is there a way for me to convert the incoming ascii into a readable integer like 64 or -114? I appreciate any help, thank you.
#include <stdlib.h>
#include <stdio.h>
#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif
#include "rs232.h"
int main()
{
int i, n,
cport_nr=0, /* /dev/ttyS0 (COM1 on windows) */
bdrate=9600; /* 9600 baud */
unsigned char buf[4096];
char mode[]={'8','N','1',0};
if(RS232_OpenComport(cport_nr, bdrate, mode))
{
printf("Can not open comport\n");
return(0);
}
while(1)
{
n = RS232_PollComport(cport_nr, buf, 4095);
if(n > 0)
{
buf[n] = 0; /* always put a "null" at the end of a string! */
for(i=0; i < n; i++)
{
if(buf[i] < 32) /* replace unreadable control-codes by dots */
{
buf[i] = '.';
}
}
printf("received %i bytes: %s\n", n, (char *)buf);
}
#ifdef _WIN32
Sleep(100);
#else
usleep(100000); /* sleep for 100 milliSeconds */
#endif
}
return(0);
}
I have an instrument which I need to talk to by RS232. I am using C and following is the code. The problem is that, when I try to read field value (reading from meter) which is 11 byte long, one read command is reading only 8 bytes and subsequently I have to issue another read command which gives me final 3 bytes. Finally I am concatenating both read buffers to make final meaningful value.
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXWAIT 30
#define BAUDRATE B9600
#define TESLAMETER "/dev/ttyS0"
#define _POSIX_SOURCE 1 /* POSIX compliant source */
#define FALSE 0
#define TRUE 1
#define NOREAD 255
volatile int STOP = FALSE;
int fd;
struct termios oldtp, newtp;
int openComPort(void)
{
fd = open(TESLAMETER, O_RDWR | O_NOCTTY |O_NDELAY );
if (fd <0)
{
perror(TESLAMETER);
return fd;
}
else
fcntl(fd,F_SETFL,0);
tcgetattr(fd,&oldtp); /* save current serial port settings */
bzero(&newtp, sizeof(newtp));
newtp.c_cflag = BAUDRATE | CS8 | CLOCAL | CREAD;
newtp.c_iflag = IGNPAR | ICRNL;
newtp.c_oflag = 0;
newtp.c_lflag = 0;//ICANON;
newtp.c_cc[VINTR] = 0; /* Ctrl-c */
newtp.c_cc[VQUIT] = 0; /* Ctrl-\ */
newtp.c_cc[VERASE] = 0; /* del */
newtp.c_cc[VKILL] = 0; /* # */
newtp.c_cc[VEOF] = 4; /* Ctrl-d */
newtp.c_cc[VTIME] = 1; /* inter-character timer unused, 0.5 seconds read timeout */
newtp.c_cc[VMIN] = 0; /* blocking or non blocking read until 1 character arrives */
tcflush(fd, TCIFLUSH);
tcsetattr(fd,TCSANOW,&newtp);
return fd;
}
float readMagField()
{
unsigned char cmd[]="FA0\r"; // Read Field
char buff2[11] = {0x00};
char buff3[11] = {0x00};
float fieldFloat = 0.00;
int n_written= 0, spot = 0, res;
do
{
n_written = write( fd, &cmd[spot], 1 );
spot += n_written;
} while (cmd[spot-1] != '\r' && n_written > 0);
if (n_written < 0)
{
printf("write() of 4 bytes failed!\n");
return FALSE;
}
else
{
//printf("Field Read Command sent successfully %d\n",n_written);
res = read(fd,buff2,11); // Reads 8 bytes
res = read(fd,buff3,11); // Reads remaining 3 bytes
fieldFloat = atof(strcat(buff2,buff3)); // Final string of 11 bytes here
return fieldFloat;
}
}
Is there something that I am doing or setting wrong? Because, I can read the complete set of characters in one go using Python serial module, but not in C. I am working on Ubuntu 12.04 LTS.
read() may return without reading the specified length.
read(2) - Linux manual page
RETURN VALUE
On success, the number of bytes read is returned (zero indicates end
of file), and the file position is advanced by this number. It is
not an error if this number is smaller than the number of bytes
requested; this may happen for example because fewer bytes are
actually available right now (maybe because we were close to end-of-
file, or because we are reading from a pipe, or from a terminal), or
because read() was interrupted by a signal. See also NOTES.
How about retrying until the desired length of data have been read?
ssize_t read2(int fd, void *buf, size_t count) {
ssize_t read_length = 0;
while (read_length < count) {
ssize_t delta = read(fd, buf + read_length, count - read_length);
if (delta == -1) return -1;
read_length += delta;
}
return read_length;
}
I am using an example code from the wiringPi library to read data from Arduino to Raspberry Pi through serial, it is displaying the data correctly with printf("%c", newChar); but I can't write the same data to a text file.
This is the whole file:
/*
Pi_Serial_test.cpp - SerialProtocol library - demo
Copyright (c) 2014 NicoHood. All right reserved.
Program to test serial communication
Compile with:
sudo gcc -o Pi_Serial_Test.o Pi_Serial_Test.cpp -lwiringPi -DRaspberryPi -pedantic -Wall
sudo ./Pi_Serial_Test.o
*/
// just that the Arduino IDE doesnt compile these files.
#ifdef RaspberryPi
//include system librarys
#include <stdio.h> //for printf
#include <stdint.h> //uint8_t definitions
#include <stdlib.h> //for exit(int);
#include <string.h> //for errno
#include <errno.h> //error output
//wiring Pi
#include <wiringPi.h>
#include <wiringSerial.h>
char device[]= "/dev/ttyAMA0";
// filedescriptor
int fd;
unsigned long baud = 9600;
unsigned long timeTemp=0;
unsigned long timeHum=0;
//unsigned long timeLight=0;
//unsigned long timeMotion=0;
//prototypes
int main(void);
void loop(void);
void setup(void);
void setup(){
printf("%s \n", "Raspberry Startup!");
fflush(stdout);
//get filedescriptor
if ((fd = serialOpen (device, baud)) < 0){
fprintf (stderr, "Unable to open serial device: %s\n", strerror (errno)) ;
exit(1); //error
}
//setup GPIO in wiringPi mode
if (wiringPiSetup () == -1){
fprintf (stdout, "Unable to start wiringPi: %s\n", strerror (errno)) ;
exit(1); //error
}
}
void loop() {
// Temperature every 3 seconds
if(millis()-timeTemp>=3000){
serialPuts (fd, "05\n");
// you can also write data from 0-255
// 65 is in ASCII 'A'
//serialPutchar (fd, 5);
timeTemp=millis();
}
// read signal
if(serialDataAvail (fd)){
char newChar = serialGetchar (fd);
FILE * writeTemp = fopen("temp.txt", "w");
printf("%c", newChar);
fputc(newChar, writeTemp);
fflush(stdout);
fclose(writeTemp);
}
// Humidity every 4 seconds
if(millis()-timeHum>=4000){
serialPuts (fd, "06\n");
// you can also write data from 0-255
// 65 is in ASCII 'A'
//serialPutchar (fd, 5);
timeHum=millis();
}
// read signal
if(serialDataAvail (fd)){
char newChar = serialGetchar (fd);
//printf("received from ardiono \n");
printf("%c", newChar);
fflush(stdout);
}
}
// main function for normal c++ programs on Raspberry
int main(){
setup();
while(1) loop();
return 0;
}
#endif //#ifdef RaspberryPi
I've tried different commands, but I'm constantly getting errors for invalid conversions from const char* to char or to FILE.
I just need to write the data from printf("%c", newChar); in a file.
In the line fputc(&newChar, writeTemp);, you're taking a pointer to your character, converting it to int, then writing that to your file. You should just write your character; something like fputc(newChar, writeTemp);. Or fprintf(writeTemp, "%c", newchar); if you prefer printf.
fputc takes a int, not an address. The problem that you are having is because you are passing the address of newChar. change the code to
fputc(newValue, tempFile);
and you should be good to go.
Good luck :)
If you want a printf-like function, use fprintf.
To write your output to a file, you would write
fprintf(writeTemp, "%c", newChar);
Also, the line
char value = printf("%c", newChar);
does not make sense, since value is declared as a char but is assigned the return status from printf.
As another reply points out, the arguments to fputc() are also wrong. You can write
fputc(newChar, writeTemp);
Using append instead of write somehow fixed the problem:
FILE * writeTemp = fopen("temp.txt", "a");
I also had to remove the second request:
/*
// Humidity every 3 seconds
if(millis()-timeHum>=3000){
serialPuts (fd, "06\n");
timeHum=millis();
}
// read signal
if(serialDataAvail (fd)){
char humChar = serialGetchar (fd);
printf("%c", humChar);
fflush(stdout);
}
*/
because it was interfering with the data for some reason, even with different char variable.
Thank you for the answers.
I'm writing a simple C program that can read data from a USB port that is connected to my Arduino device. The Arduino outputs data at a baud rate of 9600 in chunks of 4 bytes.
I want the input from the Arduino to my computer to look something like this:
136.134.132.130.129.127.126.124.121.119.117.115.113.111.
However, I'm getting something like this:
271.274.281..2.4062.4022.40225.4021
Question: How do I get the input in my C program to neatly synchronize with out loosing data/ rereading data? Are there some kind of flags that could tell my program when the port has new data?
Code:
#include <stdio.h> /* Standard input/output definitions */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#include <sys/types.h>
int open_port(void)
{
int fd; /* File descriptor for the port */
fd = open("/dev/tty.usbmodemfd121", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
{
perror("open_port: Unable to open /dev/tty");
}
else
fcntl(fd, F_SETFL, 0);
struct termios options;
tcgetattr(fd,&options);
cfsetospeed(&options,B9600);
options.c_cflag |=(CLOCAL | CREAD);
tcsetattr(fd, TCSANOW, &options);
return (fd);
}
int main (){
int i;
for(i=0; i<50; i++){
fcntl(open_port(), F_SETFL, FNDELAY);
char buf[5];
size_t nbytes;
ssize_t bytes_read;
nbytes = sizeof(buf);
bytes_read = read(open_port(), buf, nbytes);
printf("%s ", buf);
buf[0]=0;
}
return 0;
}
Your program does not properly open() the serial port for reading it.
In fact it repeatedly opens it two times every iteration of the for loop.
The device should be opened only once by your program.
Instead of
for (i=0; i<50; i++) {
fcntl(open_port(), F_SETFL, FNDELAY);
bytes_read = read(open_port(), buf, nbytes);
}
the main program should be structured like
fd = open_port();
if (fd < 0) {
/* handle error condition */
}
rc = fcntl(fd, F_SETFL, FNDELAY);
if (rc < 0) {
/* handle error condition */
}
for (i=0; i<50; i++) {
bytes_read = read(fd, buf, nbytes);
if (bytes_read < 0) {
/* handle error condition */
}
}
close(fd);
Your program is too "simple". It sets only a few attributes, and doesn't bother to check the return codes of system calls.
Is this supposed to be canonical or non-canonical (aka raw) mode (i.e. is the data ASCII text or binary)?
Refer to this Serial Programming Guide for proper setup of the serial port.
read data from a USB port
USB is a bus.
The device your program reads from is a serial port attached to that USBus.
Second coding issue
Your original code may print garbage data.
nbytes = sizeof(buf);
bytes_read = read(open_port(), buf, nbytes);
printf("%s ", buf);
buf[0]=0;
The bytes returned by the read() operation are not likely to be terminated by a NULL byte, so a string operation on that read buffer could exceed the bounds of the allocated array.
Code that would not misbehave would be something like:
nbytes = sizeof(buf) - 1;
bytes_read = read(fd, buf, nbytes);
if (bytes_read < 0) {
/* handle error condition */
} else {
buf[bytes_read] = 0; /* append terminator */
printf("%s ", buf);
}
Note that nbytes is one less than the allocated size of the buffer.
This is to ensure that there is an available byte to store the string terminator byte when the read() operation returns a "full" buffer of nbytes.
For efficiency the assignment of nbytes should be performed before entering the for loop, rather than within the loop.