I'm currently doing a project on Netduino Plus 2 using .net micro framework which requires me to code for a pulse sensor. I have tried finding codes for pulse sensor but to no avail. I tried using AnalogInput codes for pulse sensor but the output values seemed wrong (there was a constant high value despite no heartbeat placed near the sensor). Please advise!
Here are my current codes for the heartbeat sensor:
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.Netduino;
namespace heartrate
{
public class Program
{
public static void Main()
{
SecretLabs.NETMF.Hardware.AnalogInput rate =
new SecretLabs.NETMF.Hardware.AnalogInput(Pins.GPIO_PIN_A0);
int sensorvalue = 0;
while (true)
{
sensorvalue = rate.Read();
Debug.Print("" + sensorvalue);
Thread.Sleep(1000);
}
}
}
}
Here are the specs of the sensor, how it looks like and how it is connected.
http://www.elecrow.com/wiki/index.php?title=Pulse_Sensor
(This tutorial is for arduino, but I think the wiring is similar to that of Netduino)
Hard to tell without specs on your pulse device and how it is attached. For Analog input & output in my latest project (https://github.com/osstekz/cncBuddy) I use classes InputPort & OutputPort (Microsoft.SPOT.Hardware)
ex:
public NESControllerAdapter(Cpu.Pin pinClk, Cpu.Pin pinLatch, Cpu.Pin pinData1/*, Cpu.Pin pinData2 = Cpu.Pin.GPIO_NONE*/) {
// Binds to all pins
this._outpClk = new OutputPort(pinClk, false);
this._outpLatch = new OutputPort(pinLatch, false);
this._inpData1 = new InputPort(pinData1, false, Port.ResistorMode.Disabled);
//if (pinData2 != Cpu.Pin.GPIO_NONE) this._inpData2 = new InputPort(pinData2, false, Port.ResistorMode.Disabled);
}
...then like your rate.Read(); loop
public int ButtonPressed() {
// Locks all parms
this._PinTick(this._outpLatch);
// Reads plug state value
for (int i = 0; i < CncBuddyShared.iTOTALNESCONTROLLERBUTTONS; ++i) {
// Read the value, if true return this index as the first pressed button
if (this._inpData1.Read() == false) return i;
// Selects the next value
this._PinTick(this._outpClk);
}
return NESCONTROLLER_PRESSEDBUTTOM_NONE;
}
Related
I was looking for a Circular Picture Box for my app and I stumbled across this code (IT IS NOT MINE) and I've tried as many times as I could but I can't find any mistake. I have followed every step that was made in the tutorial for this Rounded Picture Box so it can't be a miscopy because it was working perfectly in the tutorial.
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.ComponentModel;
namespace New_Radio_Barcelona.Controls
{
class RashiCircularPictureBox : PictureBox
{
private int border = 2;
private Color colorBorder = Color.RoyalBlue;
private Color colorBorder2 = Color.HotPink;
private DashStyle borderstyle = DashStyle.Solid;
private DashCap borderCap = DashCap.Flat;
private float gradiant = 50f;
public RashiCircularPictureBox()
{
this.Size = new Size(95, 95);
this.SizeMode = PictureBoxSizeMode.StretchImage;
}
public int Border
{
get
{
return border;
}
set
{
border = value;
this.Invalidate();
}
}
public Color ColorBorder
{
get
{
return colorBorder;
}
set
{
colorBorder = value;
this.Invalidate();
}
}
public Color ColorBorder2
{
get
{
return colorBorder2;
}
set
{
colorBorder2 = value;
this.Invalidate();
}
}
public DashStyle Borderstyle
{
get
{
return borderstyle;
}
set
{
borderstyle = value;
this.Invalidate();
}
}
public DashCap BorderCap
{
get
{
return borderCap;
}
set
{
borderCap = value;
this.Invalidate();
}
}
public float Gradiant
{
get
{
return gradiant;
}
set
{
gradiant = value;
this.Invalidate();
}
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
this.Size = new Size(this.Width, this.Width);
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
var graphic = pe.Graphics;
var rect = Rectangle.Inflate(this.ClientRectangle, -1, -1);
var rectborder = Rectangle.Inflate(rect, -border, -border);
var size = border > 0 ? border * 3 : 1;
using (var bordercolorG = new LinearGradientBrush(rectborder, colorBorder, colorBorder2, gradiant))
using (var path = new GraphicsPath())
using (var pen = new Pen(this.Parent.BackColor, border))
using (var penborder = new Pen(bordercolorG, size))
{
graphic.SmoothingMode = SmoothingMode.AntiAlias;
penborder.DashStyle = borderstyle;
penborder.DashCap = borderCap;
path.AddEllipse(rect);
this.Region = new Region(path);
graphic.DrawEllipse(pen, rect);
if (border > 0)
{
graphic.DrawEllipse(penborder, rectborder);
}
}
}
}
}
I compile the project and then try to add it to the Design tab as shown in the tutorial. It says it could not be loaded. I was trying to understand what is not working properly but I still do not find the mistake. Some help plis?
Another aspect to take into consideration is the fact that in class RashiCircularPictureBox : PictureBox puts 1 reference above the code and in public RashiCircularPictureBox() it says 0 references. It may be for this but I'm no expert on Classes and I'm stuck in this stupidity. if anyone could clear my mind about this issue I would be so grateful about it
The designer in most versions of Visual Studio up until recently has been a 32-bit process. So if the control was built as 64-bit, it wouldn’t be able to load it at design-time, but VS would still be able to create 64-bit applications that can use the 64-bit control at runtime.
This means if you build your control as 32-bit or AnyCPU, it should solve the design-time loading problem.
The release notes of Visual Studio 2022 version 17.0.0 state that “devenv.exe is now 64-bit only”. I haven’t tried this myself, but it probably means you can now use 64-bit controls at design time with the newer versions of VS.
In all cases, AnyCPU should work.
When trying to start a new waypoint mission while one is already in progress, I usually get a OpenProtocol::ErrorCode::MissionACK::WayPoint::DATA_NOT_ENOUGH error when I try to upload the first waypoint. Strangely, if I stop the mission afterwards and try uploading again, it works.
Unfortunately, I couldn't find any detailed documentation on what this error means.
Here's my code (note that it's the onboard SDK, not the mobile SDK; the code is Java calling into native code; interface generated by SWIG):
public void uploadWaypointMissionImpl(#NonNull DroneMission mission) throws DroneException{
WayPointInitSettings wpis = newMissionSettings(mission);
MissionManager missionManager = vehicle.getMissionManager();
WaypointMission wptMission;
int wpcount = missionManager.getWayptCounter();
if (wpcount > 0){
wptMission = missionManager.getWpMission();
wptMission.stop(REQUEST_TIMEOUT_SECONDS);
wptMission.init(wpis, REQUEST_TIMEOUT_SECONDS);
} else{
missionManager.initWaypoint(wpis, REQUEST_TIMEOUT_SECONDS));
wptMission = missionManager.getWpMission();
}
if (wptMission == null)
throw new DroneException("Failed to initialize mission manager");
int pointCount = mission.getNavPoints().size();
logger.i("Waypoint mission created, uploading %d points", pointCount);
for (int i = 0; i < pointCount; ++i){
WayPointSettings wp = newWayPointSettings(mission, i);
wptMission.uploadIndexData(wp, REQUEST_TIMEOUT_SECONDS).getAck(); // <-- ERROR HERE
}
}
private static WayPointInitSettings newMissionSettings(#NonNull DroneMission mission){
WayPointInitSettings wpis = new WayPointInitSettings();
wpis.setMaxVelocity(mission.getVelocityMps());
wpis.setIdleVelocity(mission.getVelocityMps());
wpis.setTraceMode((short)(!mission.isInPlace() && Prefs.drone.traceMode().get() ? 1 : 0));
wpis.setRCLostAction((short)(Prefs.drone.rcLostMode().get() ? 1 : 0));
wpis.setGimbalPitch((short)(Prefs.drone.gimbalPitchAutoMode().get() ? 1 : 0));
wpis.setYawMode((short)0);
wpis.setExecutiveTimes((short)1);
wpis.setFinishAction((short)4);
wpis.setLatitude(0.0);
wpis.setLongitude(0.0);
wpis.setAltitude(0.0f);
wpis.setIndexNumber((short)mission.getNavPoints().size());
Uint8Array reserved = new Uint8Array(16);
for (int i = 0; i < 16; ++i){
reserved.setitem(i, (short)0);
}
wpis.setReserved(reserved.cast());
return wpis;
}
private static WayPointSettings newWayPointSettings(#NonNull DroneMission mission, int index){
WayPointSettings wp = new WayPointSettings();
wp.setDamping(Prefs.drone.dampingDistanceM().get());
wp.setGimbalPitch(Prefs.drone.gimbalPitch().get().shortValue());
wp.setYaw(Prefs.drone.yawDeg().get().shortValue());
wp.setTurnMode((short)(Prefs.drone.turnModeCounterClockwise().get() ? 1 : 0));
wp.setActionTimeLimit(100);
wp.setHasAction((short)0);
wp.setActionNumber((short)0);
wp.setActionRepeat((short)0);
Uint8Array commandList = new Uint8Array(16);
Uint16Array commandParameter = new Uint16Array(16);
for (int i = 0; i < 16; ++i){
commandList.setitem(i, (short)0);
commandParameter.setitem(i, 0);
}
wp.setCommandList(commandList.cast());
wp.setCommandParameter(commandParameter.cast());
NavPoint point = mission.getNavPoints().get(index);
wp.setLongitude(point.getLocation().getLngRad());
wp.setLatitude(point.getLocation().getLatRad());
wp.setAltitude((float)Math.ceil(point.getCruisingAltitude() - mission.getTakeoffAltitudeMeters()));
wp.setIndex((short)index);
return wp;
}
Waypoint mission needs a minimum of 3 waypoints when i tried it on an android device, try adding 2 more points but note that they must have 1 meter distance between each point
Edit: I added code for making waypoints and adding them to a list
// Create a waypoint instance
Waypoint mWaypoint1 = new Waypoint(Latitude, Longitude, altitude);
//check if the mission's builder is null
if (waypointMissionBuilder != null) {
waypointList.add(mWaypoint1);
waypointMissionBuilder.waypointList(waypointList).
waypointCount(waypointList.size());
}
else {
waypointMissionBuilder = new WaypointMission.Builder();
waypointList.add(mWaypoint1);
waypointMissionBuilder.waypointList(waypointList).
waypointCount(waypointList.size());
}
You need to make a waypoint instance which has Lat,Long,Alt. give it the correct parameters and add it to the list then use the builder to config, upload and start the mission. In case the list's size is 2 or less the mission will give you a djiError when trying to use the config function.
Hi,maybe you need to call the "wptMission.stop"before you start a new waypoint mission.All the data of this mission you write is uploaded to the flight controller,only when you call the "wptMission.stop",the flight controller will know you want to call other commands.
The truth is that I have a simple tool to let the game auto run on my android phone. I want to collect the some performance data like Profiler provides, memory, draw calls, each mem allocate on each function and so on. So is there any api or tool to reach that?
As you already noticed, you can't save from the Profiler more than 300 frames of data.
The only way to save a stream of profiling data, is to write a class and attach the script to every game object in the scene.
using UnityEngine;
using UnityEngine.Profiling;
using System.Collections;
public class ProfilerDataLogger : MonoBehaviour
{
int frameCount = 0;
void Update()
{
if (Input.GetKey(KeyCode.LeftControl) && Input.GetKeyDown(KeyCode.L))
{
StopAllCoroutines();
frameCount = 0;
StartCoroutine(DataLogger());
}
}
IEnumerator DataLogger()
{
while (true)
{
string filepath = Application.persistentDataPath + "/profilerData" + frameCount + ".log";
Profiler.logFile = filepath;
Profiler.enableBinaryLog = true;
Profiler.enabled = true;
for (int i = 0; i < 300; i++)
{
yield return new WaitForEndOfFrame();
if (!Profiler.enabled)
Profiler.enabled = true;
}
frameCount++;
}
}
}
Then, you can load the log files (each containing 300 frames of data) in the Profiler, or you can write a class in order to execute the loading from the Editor.
Could someone please maybe download and see my project? It is very simple, but not working as in the tutorial.
In my project, I set IsTrigger to true in either the ThirdPersonController or the AIThirdPersonController for one of the characters. This makes the character fall down from the Plane.
I also changed one of the characters to be tagged as Player and changed the state from PATROL to CHASE but that changed nothing. The other player never chases/follows the player I am controlling and moving around.
Why are the players falling down when I set IsTrigger to true in my project?
I see in the video that the instructor is using a Maze Plane. Is that a package I should import in the Assets or is it already somewhere in the Assets? I just added regular Plane for now because I could not find a Maze Plane.
Here is a link for my project from my OneDrive. The file name is Demo AI.rar:
Project in OneDrive
Here is a link for the video tutorial I am attempting to follow. It is supposes to be simple I suppose:
Tutorial
Here is the BasicAi class I'm using in my project, the same script from the tutorial video:
using System.Collections;
using UnityStandardAssets.Characters.ThirdPerson;
public class BasicAi : MonoBehaviour {
public NavMeshAgent agent;
public ThirdPersonCharacter character;
public enum State {
PATROL,
CHASE
}
public State state;
private bool alive;
// Variables for patrolling
public GameObject[] waypoints;
private int waypointInd = 0;
public float patrolSpeed = 0.5f;
// Variable for chasing
public float chaseSpeed = 1f;
public GameObject target;
// Use this for initialization
void Start () {
agent = GetComponent<NavMeshAgent> ();
character = GetComponent<ThirdPersonCharacter>();
agent.updatePosition = true;
agent.updateRotation = false;
state = BasicAi.State.PATROL;
alive = true;
StartCoroutine ("FSM");
}
IEnumerator FSM()
{
while (alive)
{
switch (state)
{
case State.PATROL:
Patrol ();
break;
case State.CHASE:
Chase ();
break;
}
yield return null;
}
}
void Patrol()
{
agent.speed = patrolSpeed;
if (Vector3.Distance (this.transform.position, waypoints [waypointInd].transform.position) >= 2) {
agent.SetDestination (waypoints [waypointInd].transform.position);
character.Move (agent.desiredVelocity, false, false);
} else if (Vector3.Distance (this.transform.position, waypoints [waypointInd].transform.position) <= 2) {
waypointInd += 1;
if (waypointInd > waypoints.Length) {
waypointInd = 0;
}
}
else
{
character.Move (Vector3.zero, false, false);
}
}
void Chase()
{
agent.speed = chaseSpeed;
agent.SetDestination (target.transform.position);
character.Move (agent.desiredVelocity, false, false);
}
void OnTriggerEnter(Collider coll)
{
if (coll.tag == "Player")
{
state = BasicAi.State.CHASE;
target = coll.gameObject;
}
}
}
Once a collider is a trigger it no longer collides with objects, your best bet is to place a child object that has a collider and setting that to the trigger, this way the original collider will still collide with your ground.
As for your other question how are you referencing your third person character, are you dragging it from the scene into the inspector, and you also have to bake your navmesh into your scene. I haven't looked at your project as that would take a lot of time, but maybe go through the tutorial again and see how they reference the character. With the inbuilt characters you normally have to access the namespace first.
I wrote a program in Processing 2.1.2 to establish a communication via serial Port between two machines. On my laptop, it was working fine but on my desktop where more than one serial ports are available, it is not detecting my functional serial COM port.
So now I want them to appear on Combo Button and I will able to select one from them.
Can you guide me on how do I resolve this issue?
import processing.serial.*;
String input;
Serial port;
void setup() {
size(448, 299,P3D);
println(Serial.list());
port = new Serial(this,Serial.list()[0], 9600);
port.bufferUntil('\n');
}
void draw() {
background(0);
}
void serialEvent(Serial port)
{
input = port.readString();
if(input != null) {
String[] values = split(input, " ");
println(values[0]);
println(values[1]);
println(values[2]);
}
}
As mentioned in the comment, it is possible to use a UI library to display a dropdown. First you have to choose a library, like for example controlP5 which is very popular with Processing. You may choose to use Swing with a native look & feel or G4P. That's totally up to you.
After that it should be a matter of plugging the serial ports list into the dropdown and opening the serial connection on the dropdown listener/callback.
Bellow is a proof of concept sketch based on the controlP5dropdownlist example that comes with the library:
import processing.serial.*;
import controlP5.*;
ControlP5 cp5;
DropdownList serialPortsList;
Serial serialPort;
final int BAUD_RATE = 9600;
void setup() {
size(700, 400,P3D);
String[] portNames = Serial.list();
cp5 = new ControlP5(this);
// create a DropdownList
serialPortsList = cp5.addDropdownList("serial ports").setPosition(10, 10).setWidth(200);
for(int i = 0 ; i < portNames.length; i++) serialPortsList.addItem(portNames[i], i);
}
void controlEvent(ControlEvent theEvent) {
// DropdownList is of type ControlGroup.
// A controlEvent will be triggered from inside the ControlGroup class.
// therefore you need to check the originator of the Event with
// if (theEvent.isGroup())
// to avoid an error message thrown by controlP5.
if (theEvent.isGroup()) {
// check if the Event was triggered from a ControlGroup
println("event from group : "+theEvent.getGroup().getValue()+" from "+theEvent.getGroup());
//check if there's a serial port open already, if so, close it
if(serialPort != null){
serialPort.stop();
serialPort = null;
}
//open the selected core
String portName = serialPortsList.getItem((int)theEvent.getValue()).getName();
try{
serialPort = new Serial(this,portName,BAUD_RATE);
}catch(Exception e){
System.err.println("Error opening serial port " + portName);
e.printStackTrace();
}
}
else if (theEvent.isController()) {
println("event from controller : "+theEvent.getController().getValue()+" from "+theEvent.getController());
}
}
void draw() {
background(128);
}
Also notice any existing connection will be closed when choosing a new serial port and errors handling opening the serial port are handled so the program doesn't crash in case there are issues.
For example, on OSX you get bluetooth serial ports, which may or may not be available or of use:
for processing 3.3.7 doesn't work at all for one string
String portName = serialPortsList.getItem((int)theEvent.getValue()).getName();
So i spent a lot of my neurons and nervs, but my fix is getName change toString();
and
String portName = serialPortsList.getItem((int)theEvent.getValue()).toString();
I don't understand why getName() gives me "The function doesnt exist" but toString works properly. Anybody can explain?
For variable:
String[] portNames = Serial.list();
change to global variable:
String[] portNames;
In:
void setup()
change:
String[] portNames = Serial.list();
to:
portNames = Serial.list();
In code:
String portName = serialPortsList.getItem((int)theEvent.getValue()).toString();
change to:
String portName =portNames.toString();