#include #include #include #include #include #include #include #include #define DS2480B_CMDMODE 0xE3 #define DS2480B_DATAMODE 0xE1 #define CHIPERROR -1 #define BUSERROR -2 int fd; void ow_init(char *device) { struct termios attr; fd = open(device, O_RDWR | O_NOCTTY); if (fd < 0) { perror(device); exit(-1); } tcgetattr(fd, &attr); attr.c_cflag |= CLOCAL | CS8 | B9600; tcflush(fd, TCIFLUSH); tcsetattr(fd, TCSANOW, &attr); } void rs_writebyte(unsigned char byte) { if (write(fd, &byte, 1) != 1) { perror("rs_writebyte"); } usleep(10000); } void rs_flush() { tcflush(fd, TCIFLUSH); } unsigned char rs_readbyte() { unsigned char result = 0x00; int timeout = time(NULL) + 5; int count; while (time(NULL) < timeout) { count = read(fd, &result, 1); if (count < 0 && count != EAGAIN) { perror("rs_readbyte"); exit(CHIPERROR); } if (count == 1) { return result; } usleep(10000); } fprintf(stderr, "rs_readbyte timeouted\n"); exit(CHIPERROR); } void cmd_reset() { unsigned char status; rs_flush(); rs_writebyte(0xC1); // Reset, regular speed status = rs_readbyte(); if ((status & 0xCC) != 0xCC || (status & 0x10) != 0x00) { fprintf(stderr, "Invalid response to 1-wire reset: 0x%02x\n", status); exit(CHIPERROR); } int state = status & 0x03; switch(state) { case 0: fprintf(stderr, "1-wire bus is shorted\n"); exit(BUSERROR); case 1: case 2: fprintf(stderr, "Presence pulse detected\n"); return; case 3: fprintf(stderr, "No presence pulse\n"); return; } } void ow_businit() { rs_writebyte(DS2480B_CMDMODE); cmd_reset(); } int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "Usage: %s , where device is the serial device of ds2480b\n", argv[0]); } ow_init(argv[1]); ow_businit(); return 0; }