How to read data from serial port using C# - windows

I have to create as I thought pretty simple thing. I have physical button and serial port which is in my motherboard. I want to write a program which reads if button is pressed and that is it. The issue is I don't see any COM port in device manager (I use windows 10). Also I read I could receive some data from serial port if I connect 1 and 7 pin together.
Why I couldn't see COM Port and is it possible to make it work like is wrote above?

"Why I couldn't see COM Port"
Solution 1: Sometimes it's just hidden. You need to open Device Manager -> select View tab -> choose Show hidden devices. You might be able to see the Ports (COM & LPT) option.
Solution 2: Update your motherboard drivers.
Solution 3: Manually add your COM Ports. Check out this link.
"How to read data from serial port"
public static void Main()
{
SerialPort mySerialPort = new SerialPort("COM1");
mySerialPort.BaudRate = 9600;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
mySerialPort.Open();
Console.WriteLine("Press any key to continue...");
Console.WriteLine();
Console.ReadKey();
mySerialPort.Close();
}
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
}
Everytime data comes in, the DataReceivedHandler will trigger and prints your data to the console.
You can check this link out for reference.

Related

Serial Communication between two ESP32

I have found examples of basic arduino to arduino serial communication but have been unable to get those working on ESP32 boards. I am trying to make the same thing work between two ESP32's The two are connected:
esp1 esp2
gnd to gnd
tx2 to rx2
rx2 to tx2
Simple sketches:
//transmit sketch
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println("test...");
delay(1000);
}
//receive sketch
void setup() {
Serial.begin(9600);
}
void loop() {
String received = "";
while (Serial.available())
{
received = Serial.read();
Serial.println(received);
}
}
What else is required to make this work?
I think your code comes from a simpler world in which pins were always fixed and one UART was all you had available. With the ESP32 you should probably look for a solution more along these lines:
#include <HardwareSerial.h>
HardwareSerial Serial2(2); // use uart2
Serial2.begin(19200, SERIAL_8N1, 16, 17); // pins 16 rx2, 17 tx2, 19200 bps, 8 bits no parity 1 stop bit
I hope this helps. If you still have problems after this, they're likely to be either a) the board you're using doesn't use 16 & 17 for rx2 & tx2, or b) you need 10k pull-up (not series) resistors on both lines to stop them "floating" - however some boards take care of the pull-ups for you.
All the following criteria should be meet to make it work:
ESP32 board should not use the serial port you want to use to any embedded feature. So it should be free to use.
Make sure you are using the right pins:
U
Rx
Tx
Serial
40
41
Serial1
9
10
Serial2
16
17
Make sure lines are crossed, so Tx is bind to Rx on the other board and vice versa.
Make sure that the speed is the same on both board.
To see the result both ESP32 board should be connected to the PC via USB and a console should attached to the USB ports. You can use putty for this purpose to connect the USB ports. Two instances can be run for the two USB port. Make sure the speed setup in putty is the same as it is in the code.
Whatever you type in one console will be transferred and will appear on the other console.
Upload this code to both ESP32 board:
HardwareSerial &hSerial = Serial1; //can be Serial2 as well, just use proper pins
void setup()
{
Serial.begin(115200);//open serial via USB to PC on default port
hSerial.begin(115200);//open the other serial port
}
void loop()
{
if (Serial.available()) //check incoming on default serial (USB) from PC
{
hSerial.write(Serial.read()); // read it from UBS and send it to hSerial
}
if (hSerial.available()) //check incoming on other serial from the other board
{
Serial.write(hSerial.read()); //read it from hSerial and send it to UBS
}
}

Arduino not writing to file

I'd like the arduino to write to a file whenever an ajax call is made. The ajax works, but it doesn't write to the file. All other code inside the ajax handler does execute.
void handle_ajax(){
int startUrlIndex= HTTP_req.indexOf("button");
int endUrlIndex = HTTP_req.indexOf(" HTTP");
String url = HTTP_req.substring(startUrlIndex, endUrlIndex);
int startButtonIndex = url.indexOf("device-") + 7;// 7 is length of device-, I really just want the number.
int endButtonIndex = url.indexOf("&");
String button = url.substring(startButtonIndex, endButtonIndex);
int startStateIndex = url.indexOf("state=") + 6; // 6 is length of state=, I really just want the number.
String state = url.substring(startStateIndex);
int device = button.toInt();
int newState = state.toInt();
dim_light(device, newState * 12);
write_config("", "text");
}
bool write_config(String line, String text){
configFile = SD.open("config.ini", FILE_WRITE);
if(configFile){
configFile.write("Dipshit");
}
configFile.close();
Serial.println("Works.");
return true;
}
I don't see anything wrong with the code provided.
Check the basics first:
SD card is either a standard SD card or a SDHC card.
SD card is formatted with a FAT16 or FAT32 file system.
The correct pin has been used for the CS pin in the SD.begin() command. This depends on the hardware used. http://www.arduino.cc/en/Reference/SDCardNotes
The SPI is wired up correctly (pins 11, 12, and 13 on most Arduino boards).
The hardware SS pin is set as an output (even if it isn't used as the CS pin).
I know from past experience that these little Arduinos can run out of SRAM quite quickly when reading and writing to an SD card. The ReadWrite example program uses about 50% of the UNOs SRAM alone!!
To test if this is your problem, run the SD card read/write example program (with the correct CS pin in the SD.begin() command). If this works then the problem is likely that you have run out of SRAM. Try using an Arduino MEGA 2560 instead which has 4x the amount of SRAM.
Edit: The latest Arduino IDE (v1.6.8) actually calculates how much SRAM is used by global variables. It does not take into account local variables.
Found the problem: Ram
The arduino had insufficient ram at the point of opening the SD card resulting in a failure.
If anyone else ever encounters the same issue, you need 300 or more bytes of ram. Check this by serial printing FreeRam()

WPF writing/confirming write to serial port

I am writing a program which writes to a wireless device on the serial port. The firmware has a feature which will confirm the last message sent to the device was ok, so I'm trying to make use of that and update the settings readout on the GUI rather than ask the device for all of its settings every time I make a change. I think my code will explain it a little better:
// global variable
bool queryStatusOK;
//event handler response from serial port
this.QueryStatusReponseEvent += QueryStatusResponse;
private void QueryStatusResponse(byte[] packet)
{
if (packet[3] == 0) queryStatusOK = true;
else queryStatusOK = false;
}
public void setParameter(string device)
{
//send command to serial port to change a single device parameter
Thread.Sleep(100); //sleep thread so 2 commands are not sent at once
//send command to confirm previous command was received
Thread.Sleep(100); //sleep thread to give time for confirmation to receive
if (queryStatusOK)
{
//update GUI at this point
}
}
The program is not consistent. It works sometimes, but not always. Even if I extend the thread sleep to a full second to give the boolean time to update, it still sometimes will not hit it. Can anyone suggest a better way to do this?
Thanks!
Mike

How "print" (keyboard) button works?

I am very curious to know how "Print" button capture current screen? When we press "print" button what happens? How it'll capture the screen?
Please let me know if anyone know about the same.
Thanks, Jimit
ORIGINAL USE
Under command-line based operating systems such as MS-DOS, this key causes the contents of the current text mode screen memory buffer to be copied to the standard printer port, usually LPT1. In essence, whatever was currently on the screen when the key was pressed was printed. Pressing the Ctrl key in combination with Prt Sc turns on and off the "printer echo" feature. When echo is in effect, any conventional text output to the screen will be copied ("echoed") to the printer. There is also a Unicode character for print screen, U+2399 ⎙
.
MODERN USE
Newer-generation operating systems using a graphical interface tend to copy a bitmap image of the current screen to their clipboard or comparable storage area, which can be inserted into documents as a screenshot. Some shells allow modification of the exact behavior using modifier keys such as the control key.
Macintosh does not use a print screen key; instead, key combinations are used that start with ⌘ Cmd+⇧ Shift.
.
Coding
For example a C# code can run to take a screenshot:
private void PrtScr() {
Bitmap bm = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height);
Graphics g = Graphics.FromImage(bm as Image);
g.CopyFromScreen(0, 0, 0, 0, bm.Size);
bm.Save(#"C:\image.jpeg", ImageFormat.Jpeg);
}
For example Java code:
class ScreenRecorder {
public static void main(String args[]) {
try {
Toolkit tool = Toolkit.getDefaultToolkit();
Dimension d = tool.getScreenSize();
Rectangle rect = new Rectangle(d);
Robot robot = new Robot();
Thread.sleep(2000);
File f = new File("screenshot.jpg");
BufferedImage img = robot.createScreenCapture(rect);
ImageIO.write(img,"jpeg",f);
tool.beep();
} catch(Exception e){
e.printStackTrace();
}
}
}

WIA + network scanner with adf = 1 page

I am writing a program to work with a network scanner through WIA.
Everything works fine when scanning only one page. When I turn on the feeder:
foreach (WIA.Property deviceProperty in wia.Properties)
{
if (deviceProperty.Name == "Document Handling Select")
{
int value = duplex ? 0x004 : 0x001;
deviceProperty.set_Value(value);
}
}
the program receives a scan, the signal that there are still documents in the feeder and falls off with com error (scanner continues to scan).
Here's the code check the pages in the feeder:
//determine if there are any more pages waiting
Property documentHandlingSelect = null;
Property documentHandlingStatus = null;
foreach (Property prop in wia.Properties)
{
if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_SELECT)
documentHandlingSelect = prop;
if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_STATUS)
documentHandlingStatus = prop;
}
if ((Convert.ToUInt32(documentHandlingSelect.get_Value()) & 0x00000001) != 0)
{
return ((Convert.ToUInt32(documentHandlingStatus.get_Value()) & 0x00000001) != 0);
}
return false;
Getting the picture code:
imgFile = (ImageFile)WiaCommonDialog.ShowTransfer(item, wiaFormatJPEG, false);
Unfortunately could not find an example of using WIA WSD. Perhaps there are some settings to get multiple images through WSD.
I had almost the same problem using WIA 2.0 with vba to control a Brother MFC-5895CW Multi-Function Scanner.
When I transferred scans from the ADF I was not capable to catch more than 2 pictures to image-objects (and I tried probably every existing option and worked days and hours on that problem!)
The only solution I found with that scanner was to use the ShowAcquisitionWizard-method of the WIA.CommonDialog-Object to batch-transfer all scanned files to a specified folder. It was more a workaround than a satisfying solution for me because the postprocessing would have become more complicated.
Surprise surprise, I tried the same procedure on the neat-scanner of my client... ShowAcquisitionWizard delivered only one scanned page to the specified folder, the other pages disappeared.
To my second surprise with the 'CommonDialog.ShowTransfer'-method I was able to transfer all scanned documents picture by picture into image-objects in my application.

Resources