So, since I normally despise interpreted languages (Python being the sole exception so far), I've been trying to get an LED to blink on my Uno with C++ and a winform. With very similar code and the same circuit using Processing I was able to turn the LED on and off with two buttons from my computer, but am having no luck with C++.
I compiled CPPWindows to a static library and it works fine on its own; my program is the problem. I made a simple winform with two buttons, one to turn the LED on and the other off, but it does not function as intended. When I click either button, the RX light on the Uno lights up, so I know it's receiving data, but apparently not the right data. Here's what I have so far:
#include <Arduino\SerialClass.h>
#include "Send.h"
#include "led.h"
namespace ledtest {
Serial* SP = new Serial("COM3");
[STAThread]
void main(array<String^>^ args) {
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
ledtest::led form;
Application::Run(%form);
}
void sendState(int state) {
if (state == 1)
SP->WriteData("1", 1);
if (state == 0)
SP->WriteData("0", 1);
}
void readState() {
char* iState;
while (SP->IsConnected()) {
SP->ReadData(iState, 255);
printf(iState);
}
}
The button click events are as follows:
private: System::Void btnHigh_Click(System::Object^ sender, System::EventArgs^ e) {
ledtest::sendState(1);
}
private: System::Void btnLow_Click(System::Object^ sender, System::EventArgs^ e) {
ledtest::sendState(0);
}
My Arduino sketch:
int led = 12;
char* state;
// the setup routine runs once when you press reset:
void setup() {
Serial.begin(9600);
pinMode(led, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
if (Serial.available()) {
Serial.readBytes(state, 1);
if (state == "1")
digitalWrite(led, HIGH);
if (state == "0")
digitalWrite(led, LOW);
else {
Serial.println(state);
}
}
}
CPPWindows' WriteData function requires char*, so that's why I am sending "1" instead of just a 1. In the sketch I read one byte (the character "1"), and then set the pin as high or low depending on the variable "state".
However, the data sent from the C++ program is apparently not sent correctly (or I am sending it incorrecty) and the LED never turns on. Also, the C++ program never prints what the actual variable is. Even if the variable from the Uno can't be read it should at least return a "-1", but it returns nothing.
I'm all out of ideas on what to do, so any help would be appreciated. Thanks!