Problems with simplest Arduino program - arduino

Today I started what is supposed to become a great Arduino career, but I'm already stumped. I may be going crazy, but shouldn't this code blink the LED on the Mega 2560?
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
}
unsigned int count = 0;
void loop() {
if(count%2) digitalWrite(LED_BUILTIN, LOW);
else digitalWrite(LED_BUILTIN, HIGH);
delay(1);
count++;
}
I know this is not elegant for a blinking LED, but this is a stripped down example for something else, where I need a counter and modulo operations on it. The 'Blink' program works, but this here doesn't.

delay()'s argument is measured in milliseconds (not seconds), so you probably want 1000 rather than 1 to observe the blinking!
delay(1000);
Official Documentation

Related

Stop getting values from arduino after some time

I have a strange problem, I have Arduino UNO/MEGA and I need to get Gyro sensors's data and I want to see the data in the serial monitor. Seems like a simple task, I wrote a simple C program which collects data from Arduino through serial monitor I can see the data. Everything is working for few minutes and after that, it stops.
This code is supposed to calculate a distance travelled in a line using encoder (PID algorithm implemented using Gyroscope data for straight motion) after reaching desired position, machine takes a U-Turn.
It stop for a second after taking the U-Turn and then starts straight motion again. The problem I'm facing is that the gyroscope readings stop randomly while machine taking the turn. Due to this, the machine keeps rotating about that point without stopping.
#include <Wire.h>
#include <MPU6050.h>
MPU6050 mpu;
float timeStep = 0.01, yaw=0;
const int motor11=6;//LEFT MOTOR FW
const int motor12=7;//LEFT MOTOR BK
const int motor1pwm=3;
const int motor21=8;//RIGHT MOTOR FW
const int motor22=9;//RIGHT MOTOR BK
const int motor2pwm=5;
int flag1 = 0;
int thres1=120;//PWM Values
int thres2=120;
void setup()
{
Serial.begin(115200);
// Initialize MPU6050
while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
{
Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
delay(500);
}
mpu.calibrateGyro();
mpu.setThreshold(1);
pinMode(motor11, OUTPUT);
pinMode(motor12, OUTPUT);
pinMode(motor1pwm, OUTPUT);
pinMode(motor21, OUTPUT);
pinMode(motor22, OUTPUT);
pinMode(motor2pwm, OUTPUT);
}
void loop()
{
Vector norm=mpu.readNormalizeGyro();
yaw=yaw+norm.ZAxis*timeStep;
if(flag1 == 0){
straight();
}
if(flag1 == 2){
taketurn();
}
}
void straight()
{
digitalWrite(motor11, HIGH);
digitalWrite(motor12, LOW);
analogWrite(motor1pwm, thres1);
digitalWrite(motor21, HIGH);
digitalWrite(motor22, LOW);
analogWrite(motor2pwm, thres2);
delay(8000);
flag1 = 2;
}
void taketurn()
{
float setPoint = yaw - 500;
digitalWrite(motor11, HIGH);
digitalWrite(motor12, LOW);
analogWrite(motor1pwm, 120);
digitalWrite(motor21, LOW);
digitalWrite(motor22, LOW);
analogWrite(motor2pwm, 120);
while(true)
{
Vector norm = mpu.readNormalizeGyro();
yaw = yaw + norm.ZAxis * timeStep;
Serial.print("Turning Yaw= ");
Serial.println(yaw);
if(setPoint >= yaw) {
digitalWrite(motor11, LOW);
digitalWrite(motor12, LOW);
analogWrite(motor1pwm, thres2);
digitalWrite(motor21, LOW);
digitalWrite(motor22, LOW);
analogWrite(motor2pwm, thres1);
delay(2000);
break;
}
}
flag1 = 0;
}
The serial monitor just stops displaying the reading. This does not happen every time, and it is very random. I want to get proper and continuous data. Is it a logical problem or a board problem?
Normally a random crash would indicate possibly unhandled interrupts or memory overwrite, but looking at your code and it being an Arduino program, it's unlikely to be either. I don't see any divide ops either, so you are not dividing by zero. The two possible things I see is that a) you have a "while (true)" without exit, so surely that could get you into trouble, and b) perhaps your delay functions are called with a very large value unexpectedly, and the MCU is actually just delaying a long time.

Arduino Ultrasonic Sensor pulseIn is only 3 or 4

What I am trying to do is to read the value pulseIn(ECHO, HIGH), so that I eventually can convert it to centimeters, so I know how far the ultrasonic sensor is from an object. However when I read the value printed in the Serial Monitor it is only 3 or 4 and it is with no regard to how far the ultrasonic sensor is from anything. I can't even see why it would be exactly these two values or why it changes between them. I cannot figure how to solve this problem or what can cause it. I don't know whether the problem is with the code or components. However, this sensor was recently tested by someone else and it worked then, so maybe it is just me who is doing something wrong. Help?
#define SPEAKER 11
#define TRIGGER 2
#define ECHO 3
#define SPLIT 40
unsigned long duration;
int alarm1()
{
Serial.print("alarmtest");
analogWrite(SPEAKER, 100);
delay(100);
analogWrite(SPEAKER, 0);
delay(100);
analogWrite(SPEAKER, 100);
delay(100);
analogWrite(SPEAKER, 0);
delay(500);
}
void setup()
{
Serial.begin(9600);
pinMode(SPEAKER, OUTPUT);
pinMode(TRIGGER, OUTPUT);
pinMode(ECHO, INPUT);
}
void loop()
{
digitalWrite(TRIGGER, LOW);
delayMicroseconds(50);
digitalWrite(TRIGGER, HIGH);
delayMicroseconds(50);
digitalWrite(TRIGGER, LOW);
duration = pulseIn(ECHO, HIGH);
delay(200);
Serial.print(duration);
if (duration < SPLIT)
{
// alarm1();
}
}
It gave printed this as I by mistake had used the wrong ports. Problem solved. Be sure to check your connections after an extra time!

Relay pin acts differently with load

I have the following code.
void setup(){
pinMode(14, OUTPUT);
digitalWrite(14, HIGH); //Relay
}
void loop(){
if (!digitalRead(14)){
digitalWrite(10,HIGH); //LED
digitalWrite(11,LOW); //LED
}else{
digitalWrite(10, LOW);
digitalWrite(11, HIGH);
}
}
In another portion of the code the relay pin changes states and I'm monitoring that with the digitalRead portion in the loop in hopes of changing which led is on based on the state.
Now the hard part. All of that works, except when I wire the relay to a magnet. This is all for a very intricate door control system with maglocks. And for some reason with the maglock hooked up to the relay the Arduino behaves very differently. It slows to a crawl once the relay is changed. Up until then all is fine, but as soon as the relay is activated, something causes it to slow way down.
What I can't figure out is why all is fine and relay triggers without side affects, until a load is attached to it.
Any ideas? Or a better way of monitoring a relay state? (Without storing its pseudo value in a variable)
You set the pin 14 as OUTPUT, but you're trying to read from it with digitalRead.
What you want to know is the value of the register that stores the value of the port.
You could go the easy way and use an auxiliar variable that stores the pin state like this:
bool state = true;
void setup(){
pinMode(14, OUTPUT);
digitalWrite(14, state); //Relay
}
void loop(){
if (!state){
digitalWrite(10,HIGH); //LED
digitalWrite(11,LOW); //LED
}else{
digitalWrite(10, LOW);
digitalWrite(11, HIGH);
}
}
And edit the rest of the code accordingly so state changes accordingly.
The 'Hardest to understand' solution, is to read the register value. since you're using pin 14 (the same as pin A0) you have to look into the port C According to the Arduino Reference on port manipulation (Link at the end of my answer).
So you can just do this:
void setup(){
pinMode(14, OUTPUT);
digitalWrite(14, HIGH); //Relay
}
void loop(){
if (!BitRead(PORTC,0)){ //Reads bit 0 of the register of PORTC (wich is the state of pin14)
digitalWrite(10,HIGH); //LED
digitalWrite(11,LOW); //LED
}else{
digitalWrite(10, LOW);
digitalWrite(11, HIGH);
}
}
This solution is more elegant and is exactly what you need. It might be harder to come up with so if you don't remember this in the future you could always use the "state" variable method.
Reference Bit Read Operation and Arduino Reference on port manipulation for more information.

Arduino Uno DC-Motor Controller concept clarification

I just started learning Arduino. I thought about going hands on with a Robot which I want to get some autonomy in. I got stuck trying to understand the motor control for the DC motor. I've tried to look up resources but can't find one that adequately explains my problem.
I can't understand (being a comp sci undergrad) how or what I am doing wrong writing the code for the motor.
My code just for running the motors for a test is :
// MotorA
int dir1PinA = 7;
int dir2PinA = 5;
int speedPinA = 6;
//motor B
int dir1PinB = 4;
int dir2PinB = 2;
int speedPinB = 3;
void setup() {
//Serial.begin(9600);
pinMode (dir1PinA, OUTPUT);
pinMode (dir2PinA, OUTPUT);
pinMode (speedPinA,OUTPUT);
pinMode (dir1PinB, OUTPUT);
pinMode (dir2PinB, OUTPUT);
pinMode(speedPinB, OUTPUT);
// put your setup code here, to run once:
}
void loop() {
analogWrite(speedPinA, 500);
analogWrite(speedPinB, 500);
digitalWrite (dir1PinA, LOW);
digitalWrite (dir2PinA, HIGH);
digitalWrite (dir1PinB,HIGH);
digitalWrite (dir2PinB, LOW);
// put your main code here, to run repeatedly:
}
I am just trying to run the motor at a certain speed to no avail. I found a sample code that uses the same method to control the motor but has just an extra loop and variable speed.
The test code which works is :
//Motor A
int dir1PinA = 7;
int dir2PinA = 5;
int speedPinA = 6;
//motor B
int dir1PinB = 4;
int dir2PinB = 2;
int speedPinB = 3;
unsigned long time;
int speed;
int dir;
void setup ()
{
pinMode (dir1PinA, OUTPUT);
pinMode (dir2PinA, OUTPUT);
pinMode (speedPinA, OUTPUT);
pinMode (dir1PinB, OUTPUT);
pinMode (dir2PinB, OUTPUT);
pinMode (speedPinB, OUTPUT);
time = millis ();
speed = 0;
dir = 1;
}
void loop ()
{
analogWrite (speedPinA, speed);
analogWrite (speedPinB, 555 - speed);
// set direction
if (1 == dir)
{
digitalWrite (dir1PinA , LOW);
digitalWrite (dir2PinA, HIGH);
digitalWrite (dir1PinB, HIGH);
digitalWrite (dir2PinB, LOW);
}
else
{
digitalWrite (dir1PinA, HIGH);
digitalWrite (dir2PinA, LOW);
digitalWrite (dir1PinB, LOW);
digitalWrite (dir2PinB, HIGH);
}
if (millis () - time> 5000)
{
time = millis ();
speed += 20;
if (speed> 555) {speed = 0;}
if (1 == dir)
{dir = 0;}
else
{dir = 1;}
}
}
Now I understand there are loops and extra variables but theoretically they shouldn't be required to just run a motor at a certain speed. My question is that What am I missing from the top sketch that is in the second one but is absolutely critical to the running of the motor?
I want to apologize in advance if this is a noob moment but I tried and can't find any logic lol.
In the "working" Arduino code ( c++ , yes it's compiled by a c++ compiler ) one of your both motors (B) starts immediately, and the other one 5 sec after reset (or even later)?
And the immediately started motor changes direction after 5 sec?
Else, try small modifications to the working sample, towards your simplification, to get some more understanding.
E.g. first remove the "dir" change and "else" part
Okay first I will debug your code, I will make a some assumptions about your hardware since you didn't post any photos or schematics, finally I will provide a working solution.
Your Code:
So my first assumption is that your Motor has 3 pins because you're toggling two between high and low, presumably to reverse current, and then one to set the speed.
As I am guessing you know, in order to get a motor to reverse you need to flip the direction the current is going. Setting these pins high and low won't actually reverse the current. Also, the Arduino doesn't really have enough output current to drive a DC motor. You can probably slowly run one. If you want to do more you'll need an external power source.
Drive a DC motor in one direction:
This is probably the easiest one to do. You just need a transistor, diode and resistor. Here is a tutorial
Drive up to four DC motors in both directions
If you want to drive your DC motor in two directions then you need to flip the direction the current is going. This seems complex at first until you realize they've already built something for you to do this exact thing. It's called a Motor Control. It's just a shield with a few H-Bridges on it. They're pretty cheap.
I like AdaFruit's. I have a couple and I built a robot with it not to long ago.
Tutorial on how to use the Adafruit MotorShield

Restarting Arduino and keeping the variables

I would like to restart the arduino board but keeping values of some variable. My solution would be calling setup() whenever I would like to restart. Something like this:
int led = 13;
int led2 = 50;
boolean restart = false;
void setup() {
pinMode(led, OUTPUT);
pinMode(led2, OUTPUT);
if(!restart){
digitalWrite(led, LOW); // will only happen once
delay(3000);
}
digitalWrite(led, HIGH); // turn the LED on (and will be always on even after reset)
restart = true;
delay(3000);
digitalWrite(led2, HIGH); // indicate restart is called
delay(1000);
digitalWrite(led2, LOW);
setup();}
void loop() { }
I was thinking if this will cause any heavy usage in RAM. Or is there any better methods?
Thank you.
Use the EEPROM library. Have a button with an interrupt that saves the variable then read the variable in the setup() routine.
If you are getting or changing information slow enough you could constantly write the value but beware EEPROM on this chip is only certified to 100,000 writes per byte.

Resources