Controll Motor Driver HAT Waveshare with C# - c#

I am very new in this. So if anyone can help will be great. I am trying to control Motor Driver HAT Waveshare with C# via i2c from my Raspberry pi 4b. I Install Iot.Device.MotorHat NuGet package and try this example but the result is Unexpected value of duty cycle (9766, 10280).
This is the i2c addres
This is my class
using Iot.Device.MotorHat;
using System.Collections.Generic;
using System.Device.I2c;
namespace projectV2
{
public class DCMotorController : BaseClass
{
public void StartMotor()
{
using (var motorHat = new MotorHat(200, 0x40))
{
var motor = motorHat.CreateDCMotor(1);
motor.Speed = 1;
}
}
public void StopMotor()
{
using (var motorHat = new MotorHat(200, 0x40))
{
var motor = motorHat.CreateDCMotor(1);
motor.Speed = 0;
}
}
}
}

Related

Problem with connecting to server using different users Unity-Smartfoxserver

I am making a simple memory game. I have already made the game work with smartfoxserver. But when I tried to build another machine and let them run simultaneously, one player would be log out when another log in. Could you guys help me with this one. Here is the code on the client. Also is once the game start is there any way for the two machine to connect to eachother. For example showing the score from Player1 to Player2. Thank you.
using Sfs2X;
using Sfs2X.Core;
using Sfs2X.Entities.Data;
using Sfs2X.Requests;
using Sfs2X.Util;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices.ComTypes;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using Sfs2X.Requests.MMO;
public class GameController : MonoBehaviour
{
public string defaultHost = "127.0.0.1";
public int defaultTcpport = 8888;
public int defaultWsport = 8080;
public string Zonename = "BasicExamples";
public string Username = "guest";
public string Roomname = "The Lobby";
private SmartFox sfs;
void Awake()
{
SourceSprites = Resources.LoadAll<Sprite>("Sprite/GameImages");
}
void Start()
{
Login_Click();
TotalGuess = btnlist.Count / 2;
GetButton();
AddListener();
AddSprites();
shuffle(GameSprite);
}
public void Login_Click()
{
if (sfs == null || !sfs.IsConnected)
{
sfs = new SmartFox();
sfs.ThreadSafeMode = true;
sfs.AddEventListener(SFSEvent.CONNECTION, OnConnection);
sfs.AddEventListener(SFSEvent.CONNECTION_LOST, OnConnectionLost);
sfs.AddEventListener(SFSEvent.LOGIN, OnLogin);
sfs.AddEventListener(SFSEvent.LOGIN_ERROR, OnLoginError);
sfs.AddEventListener(SFSEvent.ROOM_JOIN, OnJoinRoom);
sfs.AddEventListener(SFSEvent.ROOM_JOIN_ERROR, OnJoinRoomError);
sfs.AddEventListener(SFSEvent.EXTENSION_RESPONSE, GetResult);
ConfigData cfg = new ConfigData();
cfg.Host = defaultHost;
cfg.Port = defaultTcpport;
cfg.Zone = "BasicExamples";
cfg.Debug = true;
Debug.LogError("defaultHost " + defaultHost);
Debug.LogError("defaultTcpport " + defaultTcpport);
sfs.Connect(cfg);
}
}
void OnLogin(BaseEvent evt)
{
Debug.Log("Login Success");
sfs.Send(new JoinRoomRequest("The Lobby"));
}
void OnJoinRoom(BaseEvent evt)
{
Debug.Log("Joined Room"+ evt.Params["room"]);
}
void OnJoinRoomError(BaseEvent evt)
{
Debug.Log("Join Room Error" + evt.Params["errorMessage"]);
}
void OnLoginError(BaseEvent evt)
{
Debug.Log("Login Error"+ evt.Params["errorMessage"]);
}
void OnConnection(BaseEvent evt)
{
if ((bool)evt.Params["success"])
{
Debug.Log("Connection Success");
sfs.Send(new LoginRequest(Username, "", Zonename));
}
else
{
Debug.Log("Connection Error");
}
}
void OnConnectionLost(BaseEvent evt)
{
}
Your problem is that all of your clients have the same username when you do LoginRequest.
SFS automatically disconnect other users with the same username.
You must create a unique username for all of your clients to they can connect together.
The simplest way to do this is to use the device id as a username.
sfs.Send(new LoginRequest(SystemInfo.deviceUniqueIdentifier, "", Zonename));
hope this helps.

Missing bracket in C# because of Windows IoT background task?

I have created a test app for my first Windows IoT project with raspberry pi and an ultrasonic sensor.
I have placed some sample code in it. Visual Studio tells me that I am missing a curly bracket in "public void run…", but that doesn't seem to be the problem.
Is it because of the public class within the BackgroundTaskInstance?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Http;
using Windows.ApplicationModel.Background;
using Windows.Devices.Gpio;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
// The Background Application template is documented at http://go.microsoft.com/fwlink/?LinkID=533884&clcid=0x409
namespace IoTtest
{
public sealed class StartupTask : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
public class HCSR04
{
private GpioPin triggerPin { get; set; }
private GpioPin echoPin { get; set; }
private Stopwatch timeWatcher;
public HCSR04(int triggerPin, int echoPin)
{
GpioController controller = GpioController.GetDefault();
timeWatcher = new Stopwatch();
//initialize trigger pin.
this.triggerPin = controller.OpenPin(triggerPin);
this.triggerPin.SetDriveMode(GpioPinDriveMode.Output);
this.triggerPin.Write(GpioPinValue.Low);
//initialize echo pin.
this.echoPin = controller.OpenPin(echoPin);
this.echoPin.SetDriveMode(GpioPinDriveMode.Input);
}
public double GetDistance()
{
ManualResetEvent mre = new ManualResetEvent(false);
mre.WaitOne(500);
timeWatcher.Reset();
//Send pulse
this.triggerPin.Write(GpioPinValue.High);
mre.WaitOne(TimeSpan.FromMilliseconds(0.01));
this.triggerPin.Write(GpioPinValue.Low);
return this.PulseIn(echoPin, GpioPinValue.High);
}
private double PulseIn(GpioPin echoPin, GpioPinValue value)
{
var t = Task.Run(() =>
{
//Recieve pusle
while (this.echoPin.Read() != value)
{
}
timeWatcher.Start();
while (this.echoPin.Read() == value)
{
}
timeWatcher.Stop();
//Calculating distance
double distance = timeWatcher.Elapsed.TotalSeconds * 17000;
return distance;
});
bool didComplete = t.Wait(TimeSpan.FromMilliseconds(100));
if (didComplete)
{
return t.Result;
}
else
{
return 0.0;
}
}
}
}
}
I took the code and reformatted it for you. Please change the namespace to the value you would like
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace MyIotNamespace
{
public sealed class StartupTask :IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
}
}
public class HCSR04
{
private GpioPin triggerPin { get; set; }
private GpioPin echoPin { get; set; }
private Stopwatch timeWatcher;
public HCSR04(int triggerPin, int echoPin)
{
GpioController controller = GpioController.GetDefault();
timeWatcher = new Stopwatch();
//initialize trigger pin.
this.triggerPin = controller.OpenPin(triggerPin);
this.triggerPin.SetDriveMode(GpioPinDriveMode.Output);
this.triggerPin.Write(GpioPinValue.Low);
//initialize echo pin.
this.echoPin = controller.OpenPin(echoPin);
this.echoPin.SetDriveMode(GpioPinDriveMode.Input);
}
public double GetDistance()
{
ManualResetEvent mre = new ManualResetEvent(false);
mre.WaitOne(500);
timeWatcher.Reset();
//Send pulse
this.triggerPin.Write(GpioPinValue.High);
mre.WaitOne(TimeSpan.FromMilliseconds(0.01));
this.triggerPin.Write(GpioPinValue.Low);
return this.PulseIn(echoPin, GpioPinValue.High);
}
private double PulseIn(GpioPin echoPin, GpioPinValue value)
{
var t = Task.Run(() =>
{
//Recieve pusle
while(this.echoPin.Read() != value)
{
}
timeWatcher.Start();
while(this.echoPin.Read() == value)
{
}
timeWatcher.Stop();
//Calculating distance
double distance = timeWatcher.Elapsed.TotalSeconds * 17000;
return distance;
});
bool didComplete = t.Wait(TimeSpan.FromMilliseconds(100));
if(didComplete)
{
return t.Result;
}
else
{
return 0.0;
}
}
}
}
Nested class can't exist inside functions. Place HCSR04 inside StartupTask instead.
See https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/nested-types

MEF based plugin system can't instance my plugins

I've implemented a very small plugin system based on C# with MEF. The problem is, none of my plugins are instanced. In the Aggregate-Catalog I can see my plugin listed. But, after I'll compose these parts, there isn't my plugin in the plugin list, what I'm doing wrong?
Here's a snippet of my code:
Plugin-Loader:
[ImportMany(typeof(IFetchService))]
private IFetchService[] _pluginList;
private AggregateCatalog _pluginCatalog;
private const string pluginPathKey = "PluginPath";
...
public PluginManager(ApplicationContext context)
{
var dirCatalog = new DirectoryCatalog(ConfigurationManager.AppSettings[pluginPathKey]);
//Here's my plugin listed...
_pluginCatalog = new AggregateCatalog(dirCatalog);
var compositionContainer = new CompositionContainer(_pluginCatalog);
compositionContainer.ComposeParts(this);
}
...
And here, the plugin itself:
[Export(typeof(IFetchService))]
public class MySamplePlugin : IFetchService
{
public MySamplePlugin()
{
Console.WriteLine("Plugin entered");
}
...
}
Tested working sample.
Compile class library with code inside PluginNameSpace namespace and place it to the 'Test' folder which will be inside console app exe folder.
using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.IO;
using System.Reflection;
using ConsoleApplication;
namespace ConsoleApplication
{
public interface IFetchService
{
void Write();
}
class PluginManager
{
[ImportMany(typeof(IFetchService))]
public IFetchService[] PluginList;
public PluginManager()
{
var dirCatalog = new DirectoryCatalog(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\Test");
var pluginCatalog = new AggregateCatalog(dirCatalog);
var compositionContainer = new CompositionContainer(pluginCatalog);
compositionContainer.ComposeParts(this);
}
}
class Program
{
static void Main(string[] args)
{
var pluginManager = new PluginManager();
foreach (var fetchService in pluginManager.PluginList)
{
fetchService.Write();
}
Console.ReadKey();
}
}
}
// Separate class library
namespace PluginNameSpace
{
[Export(typeof(IFetchService))]
public class MySamplePlugin : IFetchService
{
public void Write()
{
Console.WriteLine("Plugin entered");
}
}
}

The best overloaded method match has some invalid arguments C# WPF LEAP

Error 1 The best overloaded method match for 'LeapController1.LeapEventListener.LeapEventListener(LeapController1.ILeapEventDelegate)' has some invalid arguments
Error 2 Argument 1: cannot convert from 'LeapController1.MainWindow' to 'LeapController1.ILeapEventDelegate'
I am trying to update the data to the labels on the GUI and i don't know what went wrong.
This is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Leap; //using leap motion library
namespace LeapController1
{
public partial class MainWindow : Window
{
private Controller controller = new Controller();
private LeapEventListener listener;
public MainWindow()
{
InitializeComponent();
this.controller = new Controller();
this.listener = new LeapEventListener(this);
controller.AddListener(listener);
Console.ReadKey(); //prevent console output from closing
controller.RemoveListener(listener); //remove listener from controller
controller.Dispose(); //dispose controller
}
delegate void LeapEventDelegate(string EventName);
public void LeapEventNotification(string EventName)
{
if (this.CheckAccess())
{
switch (EventName)
{
case "onInit":
txtInit.Content = "Initialised";
break;
case "onConnect":
txtConnect.Content = "Connected";
this.connectHandler();
break;
case "onDisconnect":
txtConnect.Content = "Disconnected";
break;
case "onFrame":
txtFrame.Content = " on Frame";
this.movement(this.controller.Frame());
break;
}
}
else
{
Dispatcher.Invoke(new LeapEventDelegate(LeapEventNotification), new object[] { EventName });
}
}//end method LeapEventNotification
public void connectHandler()
{
this.controller.SetPolicyFlags(Controller.PolicyFlag.POLICY_IMAGES);
this.controller.SetPolicy(Controller.PolicyFlag.POLICY_BACKGROUND_FRAMES);
this.controller.EnableGesture(Gesture.GestureType.TYPE_KEY_TAP);
this.controller.EnableGesture(Gesture.GestureType.TYPE_SCREEN_TAP);
this.controller.EnableGesture(Gesture.GestureType.TYPE_SWIPE);
this.controller.EnableGesture(Gesture.GestureType.TYPE_CIRCLE);
this.controller.Config.SetFloat("Gesture.Swipe.MinLength", 100.0f);
}
public void movement(Leap.Frame frame)
{
HandList allHands = frame.Hands; //get hand data array
foreach (Hand hand in allHands) //run for each element in array
{
Leap.Vector normal = hand.PalmNormal; //get hand.PalmNormal data
Leap.Vector direction = hand.Direction; //get hand.Direction data
double pitch = direction.Pitch; //get pitch data
double pitch1 = (pitch) * (180 / Math.PI); //convert rad to deg
int finalpitch = (int)(pitch1); //nearest whole number
double roll = normal.Roll; //get roll data
double roll1 = (roll) * (180 / Math.PI); //convert rad to deg
int finalroll = (int)(roll1); //nearest whole number
txtPitch.Content = finalpitch; //assign data to label
txtRoll.Content = finalroll; //assign data to label
}
GestureList gestures = frame.Gestures(); //returns a list of gestures
for (int i = 0; i < gestures.Count(); i++) //run when gesture made
{
Gesture gesture = gestures[i]; //gesture at that instant
switch (gesture.Type) //check gesture type
{
//if gesture.Type == TYPE_SWIPE
case Gesture.GestureType.TYPE_SWIPE:
txtGesture.Content = "SWIPE";
break;
//if gesture.Type == TYPE_SCREEN_TAP
case Gesture.GestureType.TYPE_SCREEN_TAP:
txtGesture.Content = "SCREEN TAP";
break;
//if gesture.Type == TYPE_KEY_TAP
case Gesture.GestureType.TYPE_KEY_TAP:
txtGesture.Content = "KEY TAP";
break;
//if gesture.Type == neither of the above
default:
txtGesture.Content = "UNKNOWN";
break;
}
}
}
}
public interface ILeapEventDelegate
{
void LeapEventNotification(string EventName);
}
public class LeapEventListener : Listener
{
ILeapEventDelegate eventDelegate;
public LeapEventListener(ILeapEventDelegate delegateObject)
{
this.eventDelegate = delegateObject;
}
public override void OnInit(Controller controller)
{
this.eventDelegate.LeapEventNotification("onInit");
}
public override void OnConnect(Controller controller)
{
this.eventDelegate.LeapEventNotification("onConnect");
}
public override void OnDisconnect(Controller controller)
{
this.eventDelegate.LeapEventNotification("onDisconnect");
}
public override void OnFrame(Controller controller)
{
this.eventDelegate.LeapEventNotification("onFrame");
}
}
}
With this line, you are attempting to create a new LeapEventListener by passing in the current instance of your MainWindow class.
this.listener = new LeapEventListener(this);
There is no constructor for LeapEventListener that takes a MainWindow and there is no way to implicitly convert your MainWindow into a ILeapEventDelegate.
You will need to create a class that implements the interface ILeapEventDelegate. That class will need to implement behavior for the method LeapEventNotification.
Update
Charles Ward noted in a comment to this answer...
There is an example in the Leap Motion docs -- notice that the MainWindow class also implements ILeapEventDelegate.
Looking at the code in the original question, your MainWindow already implements LeapEventNotification method. All you need to do is change your class declaration to explicitly implement the ILeapEventDelegate interface.
public partial class MainWindow : Window, ILeapEventDelegate
{
...

C# speech recogntion engine recognizes everything wrong

I have been trying to make a personal assistant in my free time, and so far i have made him speak, but now i am trying to speak to him. Whenever i do however, he fails massively. When i say "Hello my name is Alexander" he recognizes "in the name is unresolved bush" or something else that is just not correct. am i doing something wrong or is the built in C# recognition engine just broken?
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Speech.Recognition;
using System.Speech.Synthesis;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TTS_Test
{
class Jarvis
{
private static SpeechSynthesizer synthezier;
private static String name;
public Jarvis()
{
synthezier = new SpeechSynthesizer();
synthezier.SelectVoiceByHints(VoiceGender.Male, VoiceAge.Senior);
synthezier.Volume = 100;
synthezier.Rate = 0;
}
private bool isFirstTime()
{
if (File.Exists("config"))
{
return false;
}else{
return true;
}
}
private void firstTimeSetup()
{
say("Hello, My name is Jarvis. It seems that this is your first time here. Please take some time to configure the application.");
Config config = new Config();
config.ShowDialog();
say("Thank you! I should be up and running now.");
}
public void initiate()
{
if (isFirstTime())
{
firstTimeSetup();
}
setupUserData();
say("Hello " + name+". How may i help you today?");
recognize();
}
public void setupUserData()
{
StreamReader reader = new StreamReader("config");
name = reader.ReadLine();
reader.Close();
}
public void say(string output)
{
synthezier.Speak(output);
}
public void recognize()
{
SpeechRecognitionEngine sr = new SpeechRecognitionEngine(new System.Globalization.CultureInfo("en-GB"));
sr.LoadGrammar(new DictationGrammar());
sr.InitialSilenceTimeout = TimeSpan.FromSeconds(5);
sr.SetInputToDefaultAudioDevice();
RecognitionResult result = sr.Recognize();
MessageBox.Show(result.Text);
}
}
}
You should train your computer to better understand you by going to the Control Panel\All Control Panel Items\Speech Recognition

Categories

Resources