43 lines
1.6 KiB
C
43 lines
1.6 KiB
C
#include <stdio.h>
|
|
#include <libserialport.h>
|
|
|
|
#define BAUDRATE 9600
|
|
#define TIMEOUT 50000 // In Microseconds (so 50 seconds time out)
|
|
|
|
int main(void){
|
|
struct sp_port *port, **port_list; // In this example port_list is never used.
|
|
|
|
/* Opening the COMPORT. First function uses the portname to then get the pointer of the port that will be used.
|
|
* Then the second function opens the port in read and write mode (ALWAYS CLOSE AT THE END OF THE PROGRAM!)
|
|
* */
|
|
sp_get_port_by_name("COM6", &port); // COM6 is an example, should be changed to match your COM port
|
|
sp_open(port, SP_MODE_READ_WRITE);
|
|
|
|
// Configure port settings (baudrate defined above, no parity, 1 stop, no flowcontrol, 8 data bits)
|
|
sp_set_baudrate(port, BAUDRATE);
|
|
sp_set_parity(port, SP_PARITY_NONE);
|
|
sp_set_stopbits(port, 1);
|
|
sp_set_flowcontrol(port, SP_FLOWCONTROL_NONE);
|
|
sp_set_bits(port, 8);
|
|
|
|
unsigned char send_byte = 0b11110111; // An example of sending information
|
|
unsigned char recv_byte;
|
|
|
|
// Send data
|
|
printf("Sending: %d", send_byte); // Lets the user know what is sent, helpful for debugging
|
|
sp_nonblocking_write(port, &send_byte, 1);
|
|
|
|
// Wait for response
|
|
int bytes_read = sp_blocking_read_next(port, &recv_byte, 1, TIMEOUT);
|
|
if (bytes_read == 1) {
|
|
printf("Received: %d\n", recv_byte);
|
|
} else {
|
|
printf("Error reading from port.\n");
|
|
}
|
|
|
|
// Close the port (unreachable in an infinite loop, but good practice)
|
|
sp_close(port);
|
|
sp_free_port(port);
|
|
|
|
return 0;
|
|
} |