I'm totally newbie about this thing and I want to know where to start..
I have a manual that specifies data link layer that includes command and response frames to access a device connected in /dev/ttyUSB0 .
Example of the given command frame is setting the baud rate
Head = 0x0A
Address = NULL/blank
Length = 0x03
Command = 0x20
Parameter = 0x00
Check = cc
Where parameter 0x00 is equal to baud rate 9600bps.
My question is how do I use this in programming? can I use it on C language?
My OS platform is ubuntu 12.04.
Any link or idea would be a great help.
UPDATE This is the command I used in read()
unsigned char rx_buffer[1024];
size_t RX_buffer_len;
ssize_t bytes_read;
int fd;
RX_buffer_len = sizeof(rx_buffer);
bytes_read = read (serial, rx_buffer, RX_buffer_len);
You could start defining the your packet message structure
// Enable 1 byte alignment
#pragma pack(1)
typedef struct
{
uint8_t Head;
uint8_t Address;
uint8_t Length;
uint8_t Command;
uint8_t Parameter;
uint8_t Check;
}typ_packet;
// Restore the original alignment
#pragma pack()
Then you can access and configure ttyUSB0. A simple example:
struct termios2 t;
int serial, baud;
// Open the uart low level device driver and set up all params
serial_fd = open("/dev/ttyUSB0", O_NOCTTY | O_NDELAY);
if (serial != -1)
{
baud = 9600;
if (ioctl(serial, TCGETS2, &t))
{
// Fails to read tty pars
exit(1);
}
t.c_cflag &= ~CBAUD;
t.c_cflag |= BOTHER;
t.c_cflag |= CSTOPB;
t.c_ospeed = baud;
// Noncanonical mode, disable signals, extended
// input processing, and echoing
t.c_lflag &= ~(ICANON | ISIG | IEXTEN | ECHO);
// Disable special handling of CR, NL, and BREAK.
// No 8th-bit stripping or parity error handling.
// Disable START/STOP output flow control.
t.c_iflag &= ~(BRKINT | ICRNL | IGNBRK | IGNCR | INLCR |
INPCK | ISTRIP | IXON | PARMRK);
// Disable all output processing
t.c_oflag &= ~OPOST;
if (ioctl(serial, TCSETS2, &t))
{
// Failed to set serial parameters
exit(1);
}
}
else
{
// Failed to open ttyUSB0
exit(1);
}
Then you can simply read from serial line by
res = read (serial_fd, rx_buffer, RX_buffer_len);
And write using
typ_packet packet;
packet.Head = 0x0A;
packet.Address = 0x00;
packet.Length = 0x03;
packet.Command = 0x20;
packet.Parameter = 0x00;
packet.Check = 0xCC;
write(serial_fd, &packet, 6);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.