我目前正在使用C编程ubuntu 12.04上的8通道usb继电器。
我已经创建了一个简单的程序,它将写入端口但是继电器没有响应。
这是我用来向继电器发送命令的程序。
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <termios.h>
//serial
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
int con;
char *portname = "/dev/ttyUSB0";
con = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
if(con < 0) {
printf("[ERROR] %d opening %s: %s", errno, portname, strerror (errno));
return -1;
}
int speed;
int baudrate = 9600;
int parity = 0;
switch(baudrate)
{
case 0:
case 9600:
speed = B9600;
break;
case 1:
case 19200:
speed = B19200;
break;
case 2:
case 38400:
speed = B38400;
break;
case 3:
case 57600:
speed = B57600;
break;
case 4:
case 115200:
speed = B115200;
break;
default:
printf("Baud rate out of range");
return -1;
}
struct termios tty;
memset (&tty, 0, sizeof tty);
if (tcgetattr (con, &tty) != 0)
{
return -1;
}
cfsetospeed (&tty, speed);
cfsetispeed (&tty, speed);
tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8; // 8-bit chars
// disable IGNBRK for mismatched speed tests; otherwise receive break
// as \000 chars
tty.c_iflag &= ~IGNBRK; // disable break processing
tty.c_lflag = 0; // no signaling chars, no echo,
// no canonical processing
tty.c_oflag = 0; // no remapping, no delays
tty.c_cc[VMIN] = 100; // read doesn't block
tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl
tty.c_cflag |= (CLOCAL | CREAD); // ignore modem controls,
// enable reading
tty.c_cflag &= ~(PARENB | PARODD); // shut off parity
tty.c_cflag |= parity;
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CRTSCTS;
if (tcsetattr (con, TCSANOW, &tty) != 0)
{
printf("error %d from tcsetattr", errno);
return -1;
}
unsigned char wbuf[1] = {0x01};
int w = write(con, wbuf, 1);
if(w < 0) {
printf("error %d: %s", errno, strerror (errno));
return -1;
} else {
printf("%d\n", w);
}
close(con);
return 0;
}
我在write()
中使用的命令是打开第一个中继灯。
write()
的返回码为1,但是继电器在代码中没有响应,这意味着灯没有亮起。
我的问题是,是否可以在不使用ftdi库的情况下与继电器进行交互?