Can't make my stepper motor run with AccelStepper Library - arduino-uno

I'm relatively new to arduino thus need your help to figure out why my stepper motor doesn't move while trying to change its direction using AccelStepper library.
Actually I could make my stepper motor rotate in one direction, but while changing the code to make it rotate clockwise and counterclockwise, the motor doesn't move at all.
Here is my code:
#include <AccelStepper.h>
int pos=16000;
AccelStepper stepper(1,4,5);
void setup() {
stepper.setMaxSpeed(6400);
stepper.setSpeed(6400);
stepper.moveTo(pos);
}
void loop() {
if (stepper.distanceToGo() == 0)
{
stepper.setCurrentPosition(0);
pos = -pos;
stepper.moveTo(pos);
}
stepper.runSpeed();
}
Will appreciate any help you can give me :)

Related

Changing the Speed of a motor in Processing/box2D

I've been making some simple games using processing and box2D using The Nature of Code as a resource.
My problem is I have gotten to a point where I have these windmills that go clockwise/counterclockwise depending on the speed of the motor (I am using PI/2 and -PI*2). I want to have it so that the user can change this speed from positive and negative by pressing a key or mouse button. Looking around online people and the box2D documentation are saying to use the function void SetMotorSpeed(float speed);, however I am not having luck figuring out how to implement this. I've tried a few ways I can think but no luck.
Currently I have this in my main file ("s" is the name of the instance of the windmill):
// Click the mouse to switch speed of motor
void mousePressed() {
s.SetMotorSpeed(s.speed);
}
And I have this in the file for the windmill:
//Set Motor Speed
void SetMotorSpeed(float speed){
speed = speed * -1;
}
This doesn't work though.
I'm fairly new to coding and this is my first post on stack-overflow so my apologies if I have done anything wrong in how I'm asking or presenting this question. I'm open to suggestions both code and etiquette wise!
Here is the code for the entire windmill:
class Seesaw {
// object is two boxes and one joint
RevoluteJoint joint;
// float speed = PI*2;
Box box1;
Box box2;
float speed = PI*2;
Seesaw(float x, float y) {
// Initialize locations of two boxes
box1 = new Box(x, y-20, 120, 10, false);
box2 = new Box(x, y, 10, 40, true);
// Define joint as between two bodies
RevoluteJointDef rjd = new RevoluteJointDef();
Vec2 offset = box2d.vectorPixelsToWorld(new Vec2(0, 60));
rjd.initialize(box1.body, box2.body, box1.body.getWorldCenter());
// Turning on a motor (optional)
rjd.motorSpeed = PI*2; // how fast?
rjd.maxMotorTorque = 1000.0; // how powerful?
rjd.enableMotor = true; // is it on?
// Create joint
joint = (RevoluteJoint) box2d.world.createJoint(rjd);
}
// Turn the motor on or off
void toggleMotor() {
joint.enableMotor(!joint.isMotorEnabled());
}
boolean motorOn() {
return joint.isMotorEnabled();
}
void SetMotorSpeed(float speed){
speed = -speed;
}
void display() {
box2.display();
box1.display();
// Draw anchor just for debug
Vec2 anchor = box2d.coordWorldToPixels(box1.body.getWorldCenter());
fill(255, 0, 0);
stroke(0);
ellipse(anchor.x, anchor.y, 4, 4);
}
}
The change in speed should be communicated to the joint. Try this:
void SetMotorSpeed(float speed) {
s.joint.setMotorSpeed(speed); // edited, processing/java uses camel-case
}
you might also be a bit more careful about naming variables. In your original post you use the same name for the local variable and the member variable, which has not the wanted effect. Most people use some naming convention for member variable to avoid this kind of very common error. Like for instance have all member variables all start with "_"
void SetMotorSpeed(float speed) {
_speed = -speed; // speed is local!
}

Enemies always clumping together in unity 2d

I'm trying to make a top-down shooter game in unity 2d. But the enemies are always clumping together. Does someone knows how to avoid it?
Here's my enemy code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
public float moveSpeed;
public float stoppingDistance;
public Transform player;
private Rigidbody2D rb;
public GameObject effect;
public int health = 3;
public static int enemyCounter;
public SpriteRenderer enemy;
public Color hurtColor;
void Start() {
rb = GetComponent<Rigidbody2D>();
player = GameObject.FindGameObjectWithTag("Player").transform;
}
void Update() {
enemyCounter = EnemySpawner.enemyCounter;
Vector2 direction = transform.position - player.position;
if (Vector2.Distance(transform.position, player.position) > stoppingDistance) {
transform.position = Vector2.MoveTowards(transform.position, player.position,
moveSpeed * Time.deltaTime);
}
else if (Vector2.Distance(transform.position, player.position) > stoppingDistance) {
transform.position = this.transform.position;
}
}
IEnumerator Flash(){
enemy.color = hurtColor;
yield return new WaitForSeconds(0.01f);
enemy.color = Color.red;
}
void OnCollisionEnter2D(Collision2D other) {
if (other.gameObject.tag == "Bullet") {
StartCoroutine(Flash());
health -= 1;
}
if (health <= 0) {
GameObject DestroyEnemy = Instantiate(effect, transform.position, Quaternion.identity);
Destroy(this.gameObject);
Destroy(DestroyEnemy, 2f);
}
}
}
The enemies is moving towards the player, but they clump together when I move the player. I really need help.
If the enemies are moving in straight line to the player they will always clump up. If you want to ensure a minimal distance between enemies you could consider using a second larger collider on another layer but this will might end up looking bad and could make some exploits possible if too big.
The other alternative would be to change the behaviour of the enemies. Making an enemy move depending on the position of the other enemies seems complicated therefore i would simply try to add some randomness to their behaviour. Here are some ideas you could try:
-(would be my first try) switch randomly between two behaviours, 1: move straight to the player (always if very close to player), 2: move in a random direction (sometimes when further away from the player)
-don't give all your enemies the same speed
-make them move towards the player + a small random angle away from the player if far away
-...
To sum it up you will need an improved behaviour and there isn't a single solution.

Can I make my enemy run towards the player faster in this code? (Unity)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class Enemy : MonoBehaviour
{
public NavMeshAgent Ninja;
public GameObject Player;
public float NinjaDistanceRun = 30.0f;
void Start()
{
Ninja = GetComponent<NavMeshAgent>();
}
void Update()
{
float distance = Vector3.Distance(transform.position, Player.transform.position);
//Run towards player
if(distance < NinjaDistanceRun)
{
Vector3 dirToPlayer = transform.position - Player.transform.position;
Vector3 newPos = transform.position - dirToPlayer;
Ninja.SetDestination(newPos);
}
}
}
The code shown above is what I use to make the enemy follow the player when in range. Can I make my enemy go faster without trashing this whole script and making a new one that has a different line of thought?
Set the maximum speed for your ninja(NavMeshAgent.speed). Here is the documentation for more information:
https://docs.unity3d.com/ScriptReference/AI.NavMeshAgent-speed.html
In the START method you can set a new speed to your Navmesh agent, and this character will walk or run in the player direction.

3-wheel robot not moving back or left using voice commands

I am working on 3-wheel robot. I want to move my robot front, back, right, left using voice commands. I am using arduino electronics as my mobile app. By using that app I want to control my robot. I am using an arduino uno board and L293D motor driver. Below is my code for 3-wheel robot:
String readvoice;
void setup() {
//BT.begin(9600);
Serial.begin(9600);
pinMode(7, OUTPUT);
digitalWrite(7, HIGH);
}
//-----------------------------------------------------------------------//
void loop() {
while (Serial.available()) { //Check if there is an available byte to read
delay(10); //Delay added to make thing stable
char c = Serial.read(); //Conduct a serial read
readvoice += c; //build the string- "forward", "reverse", "left" and "right"
}
if (readvoice.length() > 0) {
Serial.println(readvoice);
if (readvoice == "go")
{
//Serial.println("front"); //Writing values to motor driver
digitalWrite(4,HIGH);
digitalWrite(5,LOW);
digitalWrite(7,LOW);
digitalWrite(6,HIGH);
}
if (readvoice == "left")
{
//Serial.println("left");
digitalWrite(4,HIGH);
digitalWrite(5,LOW);
digitalWrite(7,HIGH);
digitalWrite(6,LOW);
}
if(readvoice == "right")
{
//Serial.println("right");
digitalWrite(4,LOW);
digitalWrite(5,HIGH);
digitalWrite(7,LOW);
digitalWrite(6,HIGH);
}
if (readvoice == "back")
{
//Serial.println("back");
digitalWrite(4,LOW);
digitalWrite(5,HIGH);
digitalWrite(7,HIGH);
digitalWrite(6,LOW);
}
if (readvoice == "stop")
{
//Serial.println("stop");
digitalWrite(4,LOW);
digitalWrite(5,LOW);
digitalWrite(7,LOW);
digitalWrite(6,LOW);
}
readvoice = "";
}
}
I kept all the connections correctly, but my robot is able to move only right and front. I am not able to run my robot either left or back. Is there any problem in the code? Or any problem with hardware. If i had any problem with hardware, my robot should not move front or right either, but it is moving. Any idea what is wrong with back and left?

Networking rotation sync

My Unity version is 5.2.3f1, I m trying to sync the rotation of a child gameobject, in local works perfectly fine but it doesnt show up in other clients. I tried everything I could find and nothing.
The reason of this is to rotate a FPS body, so, I m trying to rotate Spine2 (Rotate the camera is not my best solution). I m using a Mixamo character to test, in the end I will have Mixamo auto-rigged charscters so everything I make here will be compatible.
I tried to use the Network Transform Rigidbody 3D and it only sync the character itself, not Spine2, I have tried Network Transform Child, and an official skeleton sync.
In the script part, I have tried a lot of things, the most promising one was this:
[SyncVar]
private Quaternion syncPlayerRotation;
[SerializeField]
private Transform playerTransform;
[SerializeField]
private float lerpRate = 15f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void LateUpdate () {
TransmitRotations();
LerpRotations();
}
void LerpRotations()
{
if (!isLocalPlayer)
playerTransform.localRotation = Quaternion.Lerp(playerTransform.localRotation, syncPlayerRotation, Time.deltaTime * lerpRate);
}
[Command]
void CmdProvideRotationsToServer(Quaternion playerRot)
{
syncPlayerRotation = playerRot;
}
[Client]
void TransmitRotations()
{
if (isLocalPlayer)
{
CmdProvideRotationsToServer(playerTransform.localRotation);
}
}
Its from UNET tutorial series on youtube, Gamer To Game Developer user.
I attached it to Spine2 and still dont work, but when I attached it to the main character, it worked.
Also tried this:
void OnSerializeNetworkView(BitStream stream, NetworkMessageInfo info)
{
Vector3 syncPosition = Vector3.zero;
if (stream.isWriting)
{
syncPosition = Spine.GetComponent<Rigidbody>().position;
stream.Serialize(ref syncPosition);
}
else
{
stream.Serialize(ref syncPosition);
Spine.GetComponent<Rigidbody>().position = syncPosition;
}
}
But I think it was for an older version of Unity.
To make the rotations I m using A Free Simple Smooth Mouselook
I edited it, this lines:
if (Input.GetMouseButton(1))
{
var xRotation = Quaternion.AngleAxis(-_mouseAbsolute.y, targetOrientation * Vector3.forward);
transform.localRotation = xRotation;
}
else
{
var xRotation = Quaternion.AngleAxis(-_mouseAbsolute.y, targetOrientation * Vector3.right);
transform.localRotation = xRotation;
}
Basicly, I changed Vector3.right to Vector3.forward and converted the Vector3.right only if the right mouse button is not pressed. The script is attached to Spine2 and its activated on the start if(isLocalPlayer) by script.
There's a pic of the current hierarchy:
(some cameras are there only to test, the main camera is FirstPersonCamera, extracted from the standard assets)
I noticed that if I debug log the Spine2 rotation, it only gives me values from 0 to 1.

Resources