Adjusting Brightness with C++

Hello,

My intention is to control the brightness (between 0-255) of an LED connected to PWM pin 9 using C++.Net.
I have the code, but in C#.Net. I'm trying to convert this code to C++, but I don't know to convert the last two lines.
This topic is the same given by Pantzmaster in "C#.Net Adjusting Brightness".
Can anyone help me?

My code is this:

#pragma once

namespace CONTROLLED {

	using namespace System;
	using namespace System::ComponentModel;
	using namespace System::Collections;
	using namespace System::Windows::Forms;
	using namespace System::Data;
	using namespace System::Drawing;
	using namespace System::IO::Ports;

	/// <summary>
	/// Summary for Form1
	/// </summary>
	public ref class Form1 : public System::Windows::Forms::Form
	{
	public:
		Form1(void)
		{
			InitializeComponent();
			serialPort1->PortName = "COM5";
			serialPort1->BaudRate = 9600;
			serialPort1->Open(); //
			ButtonOn->Enabled = false;
			Brightness->Enabled=false; //Cannot adjust brightness until the LED is "on"
			if(!serialPort1->IsOpen)
			{
				MessageBox::Show("Could not open port");
			}
			//
			//TODO: Add the constructor code here
			//
		}

	protected:
		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		~Form1()
		{
			if (components)
			{
				delete components;
			}
		}
	private: System::Windows::Forms::Button^  ButtonOn;
	private: System::Windows::Forms::Button^  ButtonOff;
	protected: 

	protected: 

	protected: 

	private: System::Windows::Forms::TextBox^  Brightness;

	private: System::Windows::Forms::Label^  label1;
	private: System::Windows::Forms::TrackBar^  trackBar1;
	private: System::IO::Ports::SerialPort^  serialPort1;
	private: System::Windows::Forms::Label^  label2;
	private: System::ComponentModel::IContainer^  components;

	private:
		/// <summary>
		/// Required designer variable.
		/// </summary>


#pragma region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		void InitializeComponent(void)
		{
			this->components = (gcnew System::ComponentModel::Container());
			this->ButtonOn = (gcnew System::Windows::Forms::Button());
			this->ButtonOff = (gcnew System::Windows::Forms::Button());
			this->Brightness = (gcnew System::Windows::Forms::TextBox());
			this->label1 = (gcnew System::Windows::Forms::Label());
			this->trackBar1 = (gcnew System::Windows::Forms::TrackBar());
			this->serialPort1 = (gcnew System::IO::Ports::SerialPort(this->components));
			this->label2 = (gcnew System::Windows::Forms::Label());
(cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->trackBar1))->BeginInit();
			this->SuspendLayout();
			// 
			// ButtonOn
			// 
			this->ButtonOn->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 8.25F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, 
				static_cast<System::Byte>(0)));
			this->ButtonOn->Location = System::Drawing::Point(49, 50);
			this->ButtonOn->Name = L"ButtonOn";
			this->ButtonOn->Size = System::Drawing::Size(126, 38);
			this->ButtonOn->TabIndex = 0;
			this->ButtonOn->Text = L"ON";
			this->ButtonOn->UseVisualStyleBackColor = true;
			this->ButtonOn->Click += gcnew System::EventHandler(this, &Form1::ButtonOn_Click);
			// 
			// ButtonOff
			// 
this->ButtonOff->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 8.25F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, 
				static_cast<System::Byte>(0)));
			this->ButtonOff->Location = System::Drawing::Point(351, 50);
			this->ButtonOff->Name = L"ButtonOff";
			this->ButtonOff->Size = System::Drawing::Size(127, 38);
			this->ButtonOff->TabIndex = 1;
			this->ButtonOff->Text = L"OFF";
			this->ButtonOff->UseVisualStyleBackColor = true;
			this->ButtonOff->Click += gcnew System::EventHandler(this, &Form1::ButtonOff_Click);
			// 
			// Brightness
			// 
			this->Brightness->Location = System::Drawing::Point(229, 194);
			this->Brightness->Name = L"Brightness";
			this->Brightness->Size = System::Drawing::Size(79, 20);
			this->Brightness->TabIndex = 2;
			// 
			// label1
			// 
			this->label1->AutoSize = true;
this->label1->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 8.25F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, 
				static_cast<System::Byte>(0)));
			this->label1->Location = System::Drawing::Point(139, 201);
			this->label1->Name = L"label1";
			this->label1->Size = System::Drawing::Size(84, 13);
			this->label1->TabIndex = 3;
			this->label1->Text = L"Brightness";
			// 
			// trackBar1
			// 
			this->trackBar1->Location = System::Drawing::Point(163, 124);
			this->trackBar1->Maximum = 255;
			this->trackBar1->Name = L"trackBar1";
			this->trackBar1->Size = System::Drawing::Size(215, 45);
			this->trackBar1->TabIndex = 4;
			this->trackBar1->Scroll += gcnew System::EventHandler(this, &Form1::trackBar1_Scroll);
			// 
			// serialPort1
			// 
			this->serialPort1->PortName = L"COM5";
			this->serialPort1->ReadTimeout = 500;
			this->serialPort1->WriteTimeout = 500;
			// 
			// label2
			// 
			this->label2->AutoSize = true;
			this->label2->Location = System::Drawing::Point(375, 201);
			this->label2->Name = L"label2";
			this->label2->Size = System::Drawing::Size(0, 13);
			this->label2->TabIndex = 5;
			// 
			// Form1
			// 
			this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
			this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
			this->ClientSize = System::Drawing::Size(525, 402);
			this->Controls->Add(this->label2);
			this->Controls->Add(this->trackBar1);
			this->Controls->Add(this->label1);
			this->Controls->Add(this->Brightness);
			this->Controls->Add(this->ButtonOff);
			this->Controls->Add(this->ButtonOn);
			this->Name = L"Form1";
			this->Text = L"Form1";
this->FormClosed += gcnew System::Windows::Forms::FormClosedEventHandler(this, &Form1::Form1_FormClosed);
(cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->trackBar1))->EndInit();
			this->ResumeLayout(false);
			this->PerformLayout();

		}
#pragma endregion
	
private: System::Void ButtonOn_Click(System::Object^  sender, System::EventArgs^  e) {
			 Brightness->Enabled=true;
			 ButtonOn->Enabled = false;
			 ButtonOff->Enabled = true;
			 //Writes "1" to the serial port, the arduino sees this and turns the LED on
			 serialPort1->Write("1");
			 label2->Text="LED on";
			 label2->BackColor = Color::Green;
		 }
private: System::Void ButtonOff_Click(System::Object^  sender, System::EventArgs^  e) {
//When "Off" button is clicked, disable the Textbox "Brightness" and the "Change" button. Enables "On" button
			 Brightness->Enabled=false;
			 ButtonOn->Enabled = true;
			 ButtonOff->Enabled = false;
			 serialPort1->Write("0");
			 label2->Text="LED off";
			 label2->BackColor = Color::Red;
		 }
private: System::Void Form1_FormClosed(System::Object^  sender, System::Windows::Forms::FormClosedEventArgs^  e) {
			 //If we close the form and the port is open, close it.
			 if(serialPort1->IsOpen)
			 {
				 serialPort1->Close();
			 }
		 }
private: System::Void trackBar1_Scroll(System::Object^  sender, System::EventArgs^  e) {
                         Brightness->Text = trackBar1->Value.ToString();
			 byte[] data = {Convert.ToByte(trackBar1.Value)}; //code in C# (How to convert into c++?)
			 serialPort1.Write(data, 0, 1);//code in C# (How to convert into c++?)
					 }
};
}

Here´s the arduino code:

int ledPin = 9; 

void setup()  
{                
  pinMode(9, OUTPUT);
  Serial.begin(9600); 
}

void loop()                    
{
  if(Serial.available())
  {  
    
   char incomingChar = Serial.read(); 

//your protocol goes here

static unsigned char PWMValue = 255;
switch(incomingChar)
{
case '1':
 // led is ON
 analogWrite(ledPin, PWMValue);
 break;
 
case '0':
 // led is OFF
 analogWrite(ledPin, 0);
 break;
 
 default:
 //Set PWM
 PWMValue = incomingChar;
 //Need to check the LED is on first or, set the C# app to app to disable brightness level
 //when LED is off;
 analogWrite(ledPin, PWMValue);
   }      
  }
}

Thanks!

nUyQigs.png

but I don't know to convert the last two lines.

The last two lines are:

};
}

It's difficult to believe that you are having trouble converting those to C++.

For me the first:

byte[] data = {Convert.ToByte(trackBar1.Value)};

in

byte data[0];
data[0]=(byte)trackBar1.value;

but an array is strange.

byte data=(byte)trackBar1.value;
serialPort1.Write(data);

For second try simply writing only data variable

Hello,

My intention is to control the brightness (between 0-255) of an LED connected to PWM pin 9 using C++.Net.
I have the code, but in C#.Net. I'm trying to convert this code to C++, but I don't know to convert these two lines:

byte[] data = {Convert.ToByte(trackBar1.Value)};// code in C#

serialPort1.Write(data, 0, 1);//code in C#

This topic is the same given by Pantzmaster in "C#.Net Adjusting Brightness".
Can anyone help me?

My code is this:

namespace CONTROLLED {

	using namespace System;
	using namespace System::ComponentModel;
	using namespace System::Collections;
	using namespace System::Windows::Forms;
	using namespace System::Data;
	using namespace System::Drawing;
	using namespace System::IO::Ports;

	/// <summary>
	/// Summary for Form1
	/// </summary>
	public ref class Form1 : public System::Windows::Forms::Form
	{
	public:
		Form1(void)
		{
			InitializeComponent();
			serialPort1->PortName = "COM5";
			serialPort1->BaudRate = 9600;
			serialPort1->Open(); //
			ButtonOn->Enabled = false;
			Brightness->Enabled=false; //Cannot adjust brightness until the LED is "on"
			if(!serialPort1->IsOpen)
			{
				MessageBox::Show("Could not open port");
			}
			//
			//TODO: Add the constructor code here
			//
		}

	protected:
		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		~Form1()
		{
			if (components)
			{
				delete components;
			}
		}
	private: System::Windows::Forms::Button^  ButtonOn;
	private: System::Windows::Forms::Button^  ButtonOff;
	protected: 

	protected: 

	protected: 

	private: System::Windows::Forms::TextBox^  Brightness;

	private: System::Windows::Forms::Label^  label1;
	private: System::Windows::Forms::TrackBar^  trackBar1;
	private: System::IO::Ports::SerialPort^  serialPort1;
	private: System::Windows::Forms::Label^  label2;
	private: System::ComponentModel::IContainer^  components;

	private:
		/// <summary>
		/// Required designer variable.
		/// </summary>


#pragma region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		void InitializeComponent(void)
		{
			this->components = (gcnew System::ComponentModel::Container());
			this->ButtonOn = (gcnew System::Windows::Forms::Button());
			this->ButtonOff = (gcnew System::Windows::Forms::Button());
			this->Brightness = (gcnew System::Windows::Forms::TextBox());
			this->label1 = (gcnew System::Windows::Forms::Label());
			this->trackBar1 = (gcnew System::Windows::Forms::TrackBar());
			this->serialPort1 = (gcnew System::IO::Ports::SerialPort(this->components));
			this->label2 = (gcnew System::Windows::Forms::Label());
(cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->trackBar1))->BeginInit();
			this->SuspendLayout();
			// 
			// ButtonOn
			// 
			this->ButtonOn->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 8.25F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, 
				static_cast<System::Byte>(0)));
			this->ButtonOn->Location = System::Drawing::Point(49, 50);
			this->ButtonOn->Name = L"ButtonOn";
			this->ButtonOn->Size = System::Drawing::Size(126, 38);
			this->ButtonOn->TabIndex = 0;
			this->ButtonOn->Text = L"ON";
			this->ButtonOn->UseVisualStyleBackColor = true;
			this->ButtonOn->Click += gcnew System::EventHandler(this, &Form1::ButtonOn_Click);
			// 
			// ButtonOff
			// 
this->ButtonOff->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 8.25F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, 
				static_cast<System::Byte>(0)));
			this->ButtonOff->Location = System::Drawing::Point(351, 50);
			this->ButtonOff->Name = L"ButtonOff";
			this->ButtonOff->Size = System::Drawing::Size(127, 38);
			this->ButtonOff->TabIndex = 1;
			this->ButtonOff->Text = L"OFF";
			this->ButtonOff->UseVisualStyleBackColor = true;
			this->ButtonOff->Click += gcnew System::EventHandler(this, &Form1::ButtonOff_Click);
			// 
			// Brightness
			// 
			this->Brightness->Location = System::Drawing::Point(229, 194);
			this->Brightness->Name = L"Brightness";
			this->Brightness->Size = System::Drawing::Size(79, 20);
			this->Brightness->TabIndex = 2;
			// 
			// label1
			// 
			this->label1->AutoSize = true;
this->label1->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 8.25F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, 
				static_cast<System::Byte>(0)));
			this->label1->Location = System::Drawing::Point(139, 201);
			this->label1->Name = L"label1";
			this->label1->Size = System::Drawing::Size(84, 13);
			this->label1->TabIndex = 3;
			this->label1->Text = L"Brightness";
			// 
			// trackBar1
			// 
			this->trackBar1->Location = System::Drawing::Point(163, 124);
			this->trackBar1->Maximum = 255;
			this->trackBar1->Name = L"trackBar1";
			this->trackBar1->Size = System::Drawing::Size(215, 45);
			this->trackBar1->TabIndex = 4;
			this->trackBar1->Scroll += gcnew System::EventHandler(this, &Form1::trackBar1_Scroll);
			// 
			// serialPort1
			// 
			this->serialPort1->PortName = L"COM5";
			this->serialPort1->ReadTimeout = 500;
			this->serialPort1->WriteTimeout = 500;
			// 
			// label2
			// 
			this->label2->AutoSize = true;
			this->label2->Location = System::Drawing::Point(375, 201);
			this->label2->Name = L"label2";
			this->label2->Size = System::Drawing::Size(0, 13);
			this->label2->TabIndex = 5;
			// 
			// Form1
			// 
			this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
			this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
			this->ClientSize = System::Drawing::Size(525, 402);
			this->Controls->Add(this->label2);
			this->Controls->Add(this->trackBar1);
			this->Controls->Add(this->label1);
			this->Controls->Add(this->Brightness);
			this->Controls->Add(this->ButtonOff);
			this->Controls->Add(this->ButtonOn);
			this->Name = L"Form1";
			this->Text = L"Form1";
this->FormClosed += gcnew System::Windows::Forms::FormClosedEventHandler(this, &Form1::Form1_FormClosed);
(cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->trackBar1))->EndInit();
			this->ResumeLayout(false);
			this->PerformLayout();

		}
#pragma endregion
	
private: System::Void ButtonOn_Click(System::Object^  sender, System::EventArgs^  e) {
			Brightness->Enabled=true;
			ButtonOn->Enabled = false;
			ButtonOff->Enabled = true;
			//Writes "1" to the serial port, the arduino sees this and turns the LED on
			serialPort1->Write("1");
			label2->Text="LED on";
			label2->BackColor = Color::Green;
		}
private: System::Void ButtonOff_Click(System::Object^  sender, System::EventArgs^  e) {
//When "Off" button is clicked, disable the Textbox "Brightness" and the "Change" button. Enables "On" button
			Brightness->Enabled=false;
			ButtonOn->Enabled = true;
			ButtonOff->Enabled = false;
			serialPort1->Write("0");
			label2->Text="LED off";
			label2->BackColor = Color::Red;
		}
private: System::Void Form1_FormClosed(System::Object^  sender, System::Windows::Forms::FormClosedEventArgs^  e) {
			//If we close the form and the port is open, close it.
			if(serialPort1->IsOpen)
			{
				serialPort1->Close();
			}
		}
private: System::Void trackBar1_Scroll(System::Object^  sender, System::EventArgs^  e) {
                         Brightness->Text = trackBar1->Value.ToString();
			byte[] data = {Convert.ToByte(trackBar1.Value)}; //code in C# (How to convert into c++?)
			serialPort1.Write(data, 0, 1);//code in C# (How to convert into c++?)
					}
};
}

Here´s the arduino code:

Code:

int ledPin = 9; 

void setup()  
{                
  pinMode(9, OUTPUT);
  Serial.begin(9600); 
}

void loop()                    
{
  if(Serial.available())
  {  
    
   char incomingChar = Serial.read(); 

//your protocol goes here

static unsigned char PWMValue = 255;
switch(incomingChar)
{
case '1':
 // led is ON
 analogWrite(ledPin, PWMValue);
 break;
 
case '0':
 // led is OFF
 analogWrite(ledPin, 0);
 break;
 
 default:
 //Set PWM
 PWMValue = incomingChar;
 //Need to check the LED is on first or, set the C# app to app to disable brightness level
 //when LED is off;
 analogWrite(ledPin, PWMValue);
   }      
  }
}

Thanks!

Please do not cross-post. This wastes time and resources as people attempt to answer your question on multiple threads.

Threads merged.

  • Moderator

Thanks nid69ita,

The following errors were reported:

error C2065: 'byte' : undeclared identifier
error C2065: 'data' : undeclared identifier
error C2228: left of '.Write' must have class/struct/union
error C2228: left of '.value' must have class/struct/union

I got:

Binary sketch size: 2,366 bytes (of a 32,256 byte maximum)

What Arduino are you compiling for, and what version of the IDE are you using?

BetoFranco51:
Thanks nid69ita,
The following errors were reported:
error C2065: 'byte' : undeclared identifier
error C2065: 'data' : undeclared identifier
error C2228: left of '.Write' must have class/struct/union
error C2228: left of '.value' must have class/struct/union

Try using unsigned char instead byte.

If errors, post all the C++ code.

Hi nid69ita,

In MSVS C++ I replace these two lines:

byte data = (byte)trackBar1.value
serialPort1.Write(data);

by these here (replace byte by insigned char):

unsigned char data = (unsigned char)trackBar1->Value;
serialPort1->Write(data);

I got the following errors:

error C2664: 'void System::IO::Ports::SerialPort::Write(cli::array<Type,dimension> ^,int,int)' :
cannot convert parameter 1 from 'unsigned char' to 'cli::array<Type,dimension> ^'
1> with
1> [
1> Type=wchar_t,
1> dimension=1
1> ]

Thank you!

The error is about second line, the first I think now is okay !?!?

You need to see where serialPort1 is declared. I think is an object of a class.
Select now the name of this class and call the help of IDE with F1.
You can search in the class documentation the method Write, if exist, if name is correct (can be "write" in lowercase) and if you have more than a write() method to call, everyone with different parameters.

Sorry is in italian, my google search found first italian language.

Write(byte[],int,int)

So, try:
unsigned char data[0];
data[0] = (unsigned char)trackBar1->Value;
serialPort1->Write(data,0,1); // 0=offset 1=number of bytes

But documentation talk about "arraySystem::Byte" but I don't know this type of class/object
See also this example: System.IO.SerialPort sample in V C++ Express
Only write, not read but in code I see some variable of type "array<System::String ^> " but I don't know this. Sorry.

This is Arduino forum not .Net forum.

For a start that is very strange code. If you get a value of 0x30 turn off the LED if you get a value of 0x31 turn it on otherwise send the ASCII value of what you receive as a brightness level. What is that supposed to do?

A lot of ASCII values are not available from a keyboard and those that are have a restricted range. It is a very silly program. In an arduino the last line would be of:-
Serial.write(data); for writing out on the default port.
If you have a mega then to write out on any of the other ports use

Serialx.write(data);

where x is the port number 1 to 3