DmxShow/main.cpp

91 lines
2.9 KiB
C++
Raw Normal View History

2024-08-08 16:14:12 -06:00
#include <iostream>
#include <windows.h>
#include <thread>
#include <chrono>
void generateRandomColors(unsigned char& r, unsigned char& g, unsigned char& b);
void sendDMXData(HANDLE hSerial, unsigned char* data, int length) {
// Start with a DMX break condition
EscapeCommFunction(hSerial, SETBREAK);
std::this_thread::sleep_for(std::chrono::milliseconds(1)); // Break duration
EscapeCommFunction(hSerial, CLRBREAK);
std::this_thread::sleep_for(std::chrono::milliseconds(1)); // Mark-after-break duration
// Write the start code followed by the DMX data
DWORD bytesWritten;
unsigned char startCode = 0;
WriteFile(hSerial, &startCode, 1, &bytesWritten, NULL);
WriteFile(hSerial, data, length, &bytesWritten, NULL);
}
int main() {
// Open the serial port
HANDLE hSerial = CreateFileA("\\\\.\\COM3", GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (hSerial == INVALID_HANDLE_VALUE) {
std::cerr << "Error opening COM3 port" << std::endl;
return 1;
}
// Configure the serial port
DCB dcbSerialParams = { 0 };
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
if (!GetCommState(hSerial, &dcbSerialParams)) {
std::cerr << "Error getting COM3 state" << std::endl;
CloseHandle(hSerial);
return 1;
}
dcbSerialParams.BaudRate = 250000; // DMX512 uses 250000 baud
dcbSerialParams.ByteSize = 8;
dcbSerialParams.StopBits = TWOSTOPBITS; // DMX512 uses 2 stop bits
dcbSerialParams.Parity = NOPARITY;
if (!SetCommState(hSerial, &dcbSerialParams)) {
std::cerr << "Error setting COM3 state" << std::endl;
CloseHandle(hSerial);
return 1;
}
// Set timeouts
COMMTIMEOUTS timeouts = { 0 };
timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutConstant = 50;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 50;
timeouts.WriteTotalTimeoutMultiplier = 10;
if (!SetCommTimeouts(hSerial, &timeouts)) {
std::cerr << "Error setting COM3 timeouts" << std::endl;
CloseHandle(hSerial);
return 1;
}
srand(static_cast<unsigned int>(time(nullptr)));
// DMX data (512 channels, all set to 255)
const int num_channels = 512;
unsigned char buffer[num_channels];
memset(buffer, 255, sizeof(buffer)); // Fill the buffer with 255
// Send DMX data in an infinite loop
while (true) {
// Generate and send random colors for channels 1, 2, and 3
generateRandomColors(buffer[0], buffer[1], buffer[2]);
// Send DMX data with random colors
sendDMXData(hSerial, buffer, num_channels);
std::this_thread::sleep_for(std::chrono::milliseconds(25)); // DMX refresh rate
}
// Close the serial port
CloseHandle(hSerial);
return 0;
}
void generateRandomColors(unsigned char& r, unsigned char& g, unsigned char& b) {
r = rand() % 256;
g = rand() % 256;
b = rand() % 256;
}