'Using SerialPort.Write(string) through DSharpPlus returns System.NullReferenceException. Literally what is wrong here?
I've been getting System.NullReferenceException whenever I tried sending a string called "woah" which has a value of "1" to a SerialPort.
I've been trying to turn on my LED light through that but it's just not working! I tried changing serialport settings or maybe directly sending "1" through it but it just doesn't work. The error is at
_serialPort.Write(woah)
Please help: Here's the code.
using System;
using System.Threading.Tasks;
using System.Threading;
using DSharpPlus;
using System.IO.Ports;
namespace OngCorptHubert{class Program{
static SerialPort _serialPort ;
static void Main(string[] args)
{
MainAsync().GetAwaiter().GetResult();
_serialPort = new SerialPort("COM4", 9600, Parity.None,8,StopBits.One);
_serialPort.Open();
}
static async Task MainAsync()
{
var discord = new DiscordClient(new DiscordConfiguration()
{
Token = "nuh uh",
TokenType = TokenType.Bot,
Intents = DiscordIntents.AllUnprivileged
});
discord.MessageCreated += async (s, e) =>
{
if (e.Message.Content.ToLower().Contains("?led-ong"))
{
Console.WriteLine("Trying to send message to port.");
string woah = "1";
_serialPort.WriteLine(woah);
Console.WriteLine("Successful!");
await e.Message.RespondAsync("LED should be on");
}
};
await discord.ConnectAsync();
await Task.Delay(-1);
}
}
}`
Solution 1:[1]
OH MY GOD I found the problem!!
I don't know how but I think I just badly initialized the SerialPort.
I removed static SerialPort _serialport; and removed _serialPort = new SerialPort("COM4", 9600, Parity.None,8,StopBits.One); _serialPort.Open();
And instead I added SerialPort _serialPort = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One); _serialPort.Open(); right before the writing command.
My LED has turned on, I love programming.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mittato |
