Control USB to Parallel Port using C# - c#

How to Control USB to Parallel Port using C#?
USB to Parallel Port: IEEE-1284 (36Pins)
IEEE-1284 Pin Configuration Image:
http://i.stack.imgur.com/b75Z5.png
OS(Operating System): Windows 7 x64
Programming Language: C#
My Code:
private void button1_Click(object sender, EventArgs e)
{
try
{
int address = System.Convert.ToInt16(textBox1.Text);
int value = System.Convert.ToInt16(textBox2.Text);
AccessPort.output(address, value);
}
catch(Exception ex)
{
MessageBox.Show("Error: " + ex.ToString());
}
}
AccessPort Class:
static class AccessPort
{
[DllImport("inpout32.dll", EntryPoint = "Out32")]
public static extern void output(int address, int value);
[DllImport("inpout32.dll", EntryPoint = "Inp32")]
public static extern int input(int adress);
}
I have LED(Light Emitting Diode) Connected to D0. When I Set Address to 1 and Value to 1 and Click Button it dont gives Error but LED wont Light UP because inpout32.dll is library for real Parallel Port but I have USB to Parallel Port or My Address and Value is Incorrect for USB to Parallel Port.
How to Light Up LED with USB to Parallel Port(LPT) using C# Programming Language ?

What is wrong there is that the port adress isn't 1. To check the port adress go to device manager, expand ports(COM & LPT), double click the lpt port(parallel port) that you want and go to the tab resources and get this value(see the link below)
http://i.imgur.com/kcEMCGY.png
then, you must change how you convert the address to a int, because the port address will be in hexadecimal:
int address = System.Convert.ToInt16(textBox1.Text, 16);
then in the address textbox just put that value(in my case it's 0378).

Related

I2C Connection Issue between RPi and Arduino Uno using Windows IOT

first StackOverflow question so hopefully its a decent one.
I'm in the process of making a sensor network using RPi's and Arduino boards. I have done this in the past using Raspbian but now have to do it using Windows IOT.
The Arduino Uno boards are connected to the Raspberry Pi using I2C communication. The problem is that my C# code produces a "Slave address is not recognized" error.
The RPi is configured as a master and the Arduino as a slave. There is no logic voltage converter, but it should work fine in this configuration as per:
https://create.arduino.cc/projecthub/phantom_override/arduino-i2c-ommunication-with-raspi-2-wiot-63d599?ref=user&ref_id=11763&offset=0
Will use a bidirectional voltage converter when I can get my hands on one.
I have tried the following:
1.) I2C connection between Windows IOT and Arduino Nano using C#
2.) Checking the connections between the RPi and the Arduino (SDA to SDA and SCL to SCL
3.) Adding 3.3V pullup resistors
4) Raspberry pi 2 and BMP280 : Slave address was not acknowledged
5.) Changing the slave address of the Arduino
6.) Swapping the both the Arduino and RPi out in case the pins were blown
7.) Digitally writing the Arduino pins low in case they were interfering with the i2c commmunication
Here is the corresponding Arduino Code:
//**********************Libraries**********************
#include <Wire.h>
//*********************Definitions*********************
#define SERIAL Serial
#define SLAVE_ADDRESS 0x40
//********************Global Variables*******************
float humidity, temperature, temp, motion;
byte ReceivedData[4];
byte Response[4];
bool DataReceived;
//Analoge Pin setup
int clockFrequency = 100000;
//***********************************Setup******************************
void setup(){
//digitalWrite(SCL, 0);
//digitalWrite(SDA, 0);
//i2c communication setup
Wire.begin(SLAVE_ADDRESS);
Wire.onReceive(receiveData);
Wire.onRequest(sendData);
//Wire.setClock(clockFrequency);
//Baud rate
Serial.begin(9600);
dht.begin();
}
//*********************************Loop*********************************
void loop()
{
getSensors();
delay(100);
}
void getSensors()
{
//sensors data retrieved
Response[0]=(byte)humidity;
Response[1]=(byte)temperature;
Response[2]=(byte)proximity;
Response[3]=(byte)motion;
}
void sendData()
{
Wire.beginTransmission(SLAVE_ADDRESS);
//Loop to iterate i2c transmissions
for (int i = 0; i <= 3; i++) {
Wire.write((uint8_t *)Response[i], sizeof(Response));
}
Wire.endTransmission();
}
And here is the corresponding C# methods for the RPi
private async Task InitI2C()
{
var settings = new I2cConnectionSettings(0x40); // Arduino address
settings.BusSpeed = I2cBusSpeed.StandardMode;
string aqs = I2cDevice.GetDeviceSelector("I2C1");
var dis = await DeviceInformation.FindAllAsync(aqs);
_device = await I2cDevice.FromIdAsync(dis[0].Id, settings);
}
private async Task GetArduino()
{
try
{
byte[] ReadBuf = new byte[32];
_device.Read(ReadBuf);
//convert buffer into floats here
}
Any help would be greatly appreciated as WIOT resources are quite scarce compared to other IOT OS's.
#MichaelXu-MSFT and #jdweng Thank you for your help. I worked out the problem. The Arduino code had unnecessary wire.beginTransmission and wire.endTransmission statements, which seem to be for sending data from master to slave on i2c, whereas I had a configuration of the master device requesting data from the slave. Just using the wire.write(data, length) length function in the sendData() ISR did the trick. I highly recommend http://www.gammon.com.au/i2c, as he has excellent i2c resources on his site.
The correction is as follows:
void sendData()
{
//Wire.beginTransmission(SLAVE_ADDRESS); remove this statement
Wire.write(Response, sizeof(Response));
//Wire.endTransmission(); remove this statement as well
}

Get unique identification value of Arduino Uno controller from C# desktop application

I'm trying to figure out, what and how can get as unique identification number or any other kind of ID equivalent from particular Arduino Uno micro-controller from C# desktop application with serial port data
In case of Uno, I have COM3 open:
myport.PortName = comPort;
myport.BaudRate = 9600;
myport.Open();
But I'm not sure, how to read such data as ID of chip, for example with EEPROM Get :
#include <EEPROM.h>
void setup() {
float f = 0.00f;
int eeAddress = 0;
Serial.begin(9600);
while (!Serial) {
}
Serial.print("Read float from EEPROM: ");
EEPROM.get(eeAddress, f);
Serial.println(f, 3);
secondTest(); //Run the next test.
}
struct MyObject {
float field1;
byte field2;
char name[10];
};
void secondTest() {
int eeAddress = sizeof(float);
MyObject customVar;
EEPROM.get(eeAddress, customVar);
Serial.println("Read custom object from EEPROM: ");
Serial.println(customVar.field1);
Serial.println(customVar.field2);
Serial.println(customVar.name);
}
void loop() {}
and C#:
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = myport.ReadExisting();
}
I get some completely misunderstood result:
Read float from EEPROM: ovf
Read custom object from EEPROM:
ovf
95
_^^]]]\\\\fedc
What must be the output variable to get unique id from particular micro-controller:
Serial.println(customVar.field2);
Serial.println(customVar.name);
Atmega328P used in official Arduino UNO does not have any factory-programmed unique ID. However, Atmega328PB does have 10 bytes long preprogrammed serial number.
Atmega328PB seems to be quite compatible with Atmega328P. Differences are described in this application note: http://ww1.microchip.com/downloads/en/AppNotes/Atmel-42559-Differences-between-ATmega328P-and-ATmega328PB_ApplicationNote_AT15007.pdf
You can read serial number with boot_signature_byte_get() function from avr/boot.h: https://www.nongnu.org/avr-libc/user-manual/group__avr__boot.html#gaf375d2543ba38dc56697b4f4bc37a717
There are boards available with Atmega328PB chip, just google for "Atmega328PB arduino".
In case you cannot change the chip, then you would need to generate and program unique ID into your chip yourself.

Receiving data via bluetooth to c# program

I'm using inTheHand library (32feet.NET).
I have a device with bluetooth enabled and I want to connect with the device to my computer and than send data from the device to computer. I then want to catch that information with my program and process it.
The device will send me 3 variables (all 3 float).
How do I catch that information with bluetooth? I never worked with bluetooth on a computer before.
I tried like this post said:
Pair bluetooth devices to a computer with 32feet .NET Bluetooth library
But don't know what I'm doing, so I can't make it work.
I'm using Visual Studio 2017 and Windows 10. I heard there are problems for Windows 10 and authenticating bluetooth devices.
Thanks for all the help!
UPDATE:
static string domaciaddress = "MY_ADDRESS";
static string tujadress = "DEVICE_ADDRESS";
//reciever
private static BluetoothEndPoint EP = new BluetoothEndPoint(BluetoothAddress.Parse(domaciaddress), BluetoothService.BluetoothBase);
private static BluetoothClient BC = new BluetoothClient(EP);
//sender
private static BluetoothDeviceInfo BTDevice = new BluetoothDeviceInfo(BluetoothAddress.Parse(tujadress));
private static NetworkStream stream = null;
static void neke231(string[] args)
{
string paircode = "paircode";
if (BluetoothSecurity.PairRequest(BTDevice.DeviceAddress, paircode))
{
Console.WriteLine("PairRequest: OK");
if (BTDevice.Authenticated)
{
Console.WriteLine("Authenticated: OK");
BC.SetPin(paircode);
BC.BeginConnect(BTDevice.DeviceAddress, BluetoothService.SerialPort, new AsyncCallback(Connect), BTDevice);
}
else
{
Console.WriteLine("Authenticated: No");
}
}
else
{
Console.WriteLine("PairRequest: No");
}
Console.ReadLine();
}
I now connect to my bluetooth like this. But I still don't know how to get those 3 floats that my device sends, and save it here in float, so I can later in program use them.
EDIT:
This code in fact doesn't work exactly... I don't know why, but it won't connect to android phone. When I run program instead of getting what I write into console, I get only BluetoothGetDeviceInfo returned: 0x80070057

Arduino UNO sending Temperature and Humidity data from DHT11 sensor to Raspberry pi 2(running windows iot core) through I2c

I have made Arduino UNO as a slave and Raspberry Pi 2 as a master. The code running on Arduino UNO is as follows :
#include "DHT.h"
#include<Wire.h>
#define DHTPIN 4 // what digital pin we're connected to
#define DHTTYPE DHT11 // DHT 11
#define SLAVE_ADDRESS 0x29
DHT dht(DHTPIN, DHTTYPE);
int t;
void setup() {
Serial.begin(9600); //setting baud rate for communication
Wire.begin(SLAVE_ADDRESS); //assigning slave with i2c at defined slave address
Wire.onRequest(sendData); //Event for sending the data through i2c
dht.begin();
}
void loop() {
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
t = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print("\n");
Wire.onRequest(sendData); // asked to send the data
delay(1000);
}
void sendData(){
Wire.write(t);
Serial.print("in send data:"+t);
}
The Raspberry Pi 2 code is written in c#. It is as follows :
using System;
using Windows.UI.Xaml.Controls;
using Windows.Devices.Enumeration;
using Windows.Devices.I2c;
using System.Diagnostics;
using System.Threading;
namespace App2
{
public sealed partial class MainPage : Page
{
private I2cDevice Device;
private Timer periodicTimer;
public MainPage()
{
this.InitializeComponent();
initcomunica();
}
private async void initcomunica()
{
var settings = new I2cConnectionSettings(0x29); // Arduino address
Debug.WriteLine(settings);
settings.BusSpeed = I2cBusSpeed.StandardMode;
Debug.WriteLine(settings.BusSpeed);
string aqs = I2cDevice.GetDeviceSelector("I2C1");
Debug.WriteLine(aqs);
var dis = await DeviceInformation.FindAllAsync(aqs);
Debug.WriteLine(dis);
Debug.WriteLine(dis[0].Id);
Device = await I2cDevice.FromIdAsync(dis[0].Id,settings );
periodicTimer = new Timer(this.TimerCallback, null, 0, 1000); // Create a timmer
}
private void TimerCallback(object state)
{
byte[] RegAddrBuf = new byte[] { 0x08 };
byte[] ReadBuf = new byte[5];
try
{
Device.Read(ReadBuf); // read the data
Debug.WriteLine(ReadBuf);
}
catch (Exception f)
{
Debug.WriteLine("error in reading from buffer"+f.Message);
}
// Converte Byte to CharArray
char[] cArray = System.Text.Encoding.UTF8.GetString(ReadBuf, 0,5).ToCharArray();
String c = new String(cArray);
Debug.WriteLine(c);
}
}
}
Connections done between Raspberry Pi 2 and Arduino UNO :
Analog pin of Arduino UNO (A4-SDA) connected to pin 5(SCL) of Raspberry Pi 2
Analog pin of Arduino UNO (A5-SCL) connected to pin 3(SDA) of Raspberry Pi 2
Used a voltage divider circuit with resistances 1K ohm and 2k ohm to give 3.3V to Pi instead of 5V.
DHT11 sensor connections with Arduino UNO.
Problem : I have deployed Universal windows app from Visual Studio on Pi code written in c# but I am getting an Exception in the code. The exception and error is as follows :
Exception thrown:
'System.Runtime.InteropServices.COMException' in mscorlib.ni.dll
WinRT information: Failed to apply connection settings to the device.
Additional information: A device attached to the system is not functioning.
Requirement : I have searched on Internet everything regarding this exception but didn't found any solution and Raspberry Pi 2 is unable to communicate with Arduino UNO.Don't know whether it is problem from Arduino side or Raspberry Pi side.
Please help me solve this problem.
It seems Your lines are wrong.
Usually SCL pin connects to SCL and SDA connects to SDA. It's not reversed like on UART.

How to detect Windows Mobile 5 Device Serial Number? (.NET CF 3.5)

We have several devices where I work (mostly Datalogic 4420 Falcon), and someone is always leaving one off the base. The battery runs dry, then they bring them back to get setup all over. (There's supposed to be a way to configure a file on the SD card to reload upon such an error, but it doesn't work very well)
When someone saves changes on the device (using my app that writes data to the SQL Server), the Serial Number is sent along with it so we can track what devices are in use where.
Each device has a Serial Number, and I have to physically (i.e. manually) write that into the Device name field, which I can read. Working code here if anyone wants to know how:
static string deviceId = null;
public static string DeviceName {
get {
if (String.IsNullOrEmpty(deviceId)) {
using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Ident", true)) {
try {
deviceId = key.GetValue("Name", "[Unnamed]").ToString();
} catch (Exception e) {
ErrorWrapper("GetDeviceName", e);
deviceId = Dns.GetHostName();
} finally {
key.Flush();
key.Close();
}
}
}
return deviceId;
}
}
I do not like the manual (i.e. Fat Finger prone) Serial Number entry. Is there some call to query the device's Serial Number, or is that vendor specific?
Datamax does make an SDK that is specific to their devices, but we don't want our applications tied down to any one manufacturer (we are already tied down to VS2008).
I'd start by trying to P/Invoke to get the device ID (KerneIoControl with IOCTL_HAL_GET_DEVICEID) and see if it matches the serial number you're after. Here's an example.
I don't know about your Datalogic 4420 Falcon device, but I work with Intermec CK30 & CK60 and I have their itc50.dll file.
Here is snippet:
[DllImport("itc50.dll")]public static extern int ITCGetSerialNumber(StringBuilder Snumber, int buffSize);
StringBuilder hwSN = new StringBuilder(12);
if (ITCGetSerialNumber(hwSN, hwSN.Capacity) >= 0)
{
;
;
}

Categories

Resources