I need some help with my arduino ramp motor code.
I am making a remote control robot. The remote has one button.
If the button is high: The motor should gradually increase its speed using pwm (Starting with pwm=0).The time period from standstill speed to maximum speed should be 1 second. Once it has reached maximum speed it should maintain the maximum speed (pwm=255).
The moment the button is released the motor should gradually decrease from the current speed to a complete standstill.
So far I have managed to write the ramp up and maintain speed part of the code; the code doesn't include the button part.
int motor;
int motorpwm=11;
int x=1;
int i;
void setup()
{
pinMode(11,OUTPUT);
Serial.begin(9600);
}
void loop()
{
for(int i=0;i<256;i=i+x)
{
analogWrite(motorpwm,i);
Serial.println(i);
if(i==255)
{
x=0;
Serial.println("PWM is maximum");
}
}
}
Please include the complete code including the button control part of the code.
I do not assure you if this is bug-free but you can try this and post your restults here, so that I can debug it for you. Here you go:
int motor;
int motorpwm = 11;
int x = 1;
int i;
int pwmValue;
void setup()
{
pinMode(11, OUTPUT);
pinMode(2, INPUT); //Button connected to Vcc and pulled down using a 10k resistor.
Serial.begin(9600);
}
void loop()
{
if (digitalRead(2)) //if button is pressed it will read High signal
{
if (pwmValue <= 255)
{
analogWrite(motorpwm, pwmValue++);
Serial.print("Going Up with value: ");
Serial.println(pwmValue);
}
else
{
Serial.println("PWM is maximum");
}
}
else
{
if (motorpwm > 0)
{
analogWrite(motorpwm, pwmValue--);
Serial.print("Going down with value: ");
Serial.print(pwmValue);
}
else
{
Serial.println("PWM is minimum");
}
}
}
Related
I'm doing a code where the timer gets triggered by a pushbutton. The problem is that nothing happens, the serial monitor doesn't show anything. I've checked all of the connections and there is no errors in the electronic components. I'm not sure what is wrong.
Thankyou
Here's the code:
int timer;
const int starttrigger = 2;
const int endtrigger = 4;
void setup() {
pinMode(starttrigger, INPUT);
pinMode(endtrigger, INPUT);
pinMode(redled, OUTPUT);
pinMode(greenled, OUTPUT);
}
void loop() {
int start_button_state = digitalRead(starttrigger);
int end_button_state = digitalRead(endtrigger);
if (start_button_state == HIGH) {
while (end_button_state == LOW){
for(timer = 0; end_button_state == HIGH; timer ++) {
Serial.println(timer);
}
}
}
}
You do not see anything in the serial monitor because you have not activating Serial communication in the first place. It needs to be done in the void setup() function.
Please add this line to your void setup function
Serial.begin(9600);
I am using Arduino Uno, I try to run servo constantly from 0 to 45 degrees when the interrupt button is pressed it should go to -30 degree and wait here. When the same button is pressed again, it should resume the constant action, which is swiping 0 to 45 degrees without <servo.h> library.
I tried to run like this:
const int servo = 11;
const int led = 13;
const int buttonPin = 2;
volatile int buttonState = 1;
void setup() {
Serial.begin(57600);
pinMode(led, OUTPUT);
pinMode(servo, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(buttonPin),Button,CHANGE);
}
void loop() {
digitalWrite(led,HIGH);
for(int i=0;i<30;i++)
{
digitalWrite(servo,HIGH);
delayMicroseconds(1500);
digitalWrite(servo,LOW);
delayMicroseconds(18500);
}
delay(2000);
for(int i=0;i<30;i++)
{
digitalWrite(servo,HIGH);
delayMicroseconds(1000);
digitalWrite(servo,LOW);
delayMicroseconds(19000);
}
delay(2000);
}
void Button()
{
digitalWrite(led,LOW);
for(int i=0;i<30;i++)
{
digitalWrite(servo,HIGH);
delayMicroseconds(1833);
digitalWrite(servo,LOW);
delayMicroseconds(18167);
}
}
I have no problem coding my own PWM for each case but it turns out, the problem is a bit complicated than I was expecting because when we try to resume, I need to disable the interrupt function when pressing the same an interrupt button somehow.
Is it possible in this way or is there a better way to implement it?
For a aspberry pi project I have buttons connected to GPIO and I want to take different actions depending on how long a button has been pressed. The following python code (extract) is working as expected:
on_button2(channel):
t1 = time.time()
# Wait for button release
while GPIO.input(channel) == 0:
pass
duration = time.time() - t1
print "duration: %f" % (duration)
if duration > 0.75:
mpd_client.previous()
else:
mpd_client.next()
GPIO.add_event_detect(BUTTON2_PIN, GPIO.FALLING, callback=on_button2, bouncetime=700);
I would like to convert this into a C program (don't ask why, I really don't like python and I'm much more familiar with C, so I'd like to do it in C)
Trying to convert this to C with wiringPi, I came up with this, but it is not working as expected:
unsigned long btn2_t0;
static void on_button_2_pressed() {
unsigned long duration, t1;
int level;
level = digitalRead(BUTTON_2_PIN);
// Debounce button
t1 = millis();
if (t1 - btn2_t0 < 700) {
return;
}
btn2_t0 = t1;
// Wait for button being released
while (digitalRead(BUTTON_2_PIN) == LOW) {
delay(100);
}
duration = millis() - t1;
if (duration > 5000) {
printf("Self destruction sequence initiated!\n");
}
else if (duration > 700) {
player_previous();
}
else {
player_next();
}
}
int main() {
// Setup WiringPi Lib
wiringPiSetupGpio();
pinMode(BUTTON_2_PIN, INPUT);
// Register callbacks on button press
wiringPiISR(BUTTON_2_PIN, INT_EDGE_FALLING, on_button_2_pressed);
for (;;) {
delay(500);
}
return 0;
}
It seems that the loop that should wait for button release is not being executed or that the while-condition is always true, and thus, duration always is zero.
Is the digitalRead(BUTTON_2_PIN) function equivalent to the GPIO.input(channel) in the python code at all?
If somebody could point me in the right direction on how to detect button press (software-debounced) and measure the duration of the button press in C.
Thanks a lot.
EDIT: Working solution
After playing around a lot and with the help of Francesco Boi I came around with a working solution, although I do not really understand why the compare logic with HIGH / LOW is swapped compared to the python code (I thought that the button press will cause the pin to FALL to LOW and releasing it would RAISE it to HIGH ...)
static void on_button_2_pressed() {
unsigned long duration;
static unsigned long button_pressed_timestamp;
int level = digitalRead(BUTTON_2_PIN);
if (level == HIGH) { // Why HIGH ?!?
button_pressed_timestamp = millis();
}
else {
duration = millis() - button_pressed_timestamp;
button_pressed_timestamp = millis();
if (duration < 100) {
// debounce...
return;
}
else if (duration < 700) {
syslog(LOG_NOTICE, ">> NEXT\n");
}
else if (duration < 3000) {
syslog(LOG_NOTICE, "<< PREV\n");
}
else {
syslog(LOG_NOTICE, "!! REBOOT\n");
}
}
}
int main() {
...
wiringPiISR(BUTTON_2_PIN, INT_EDGE_BOTH, on_button_2_pressed);
...
}
First of all you are reading the value of the pin into level then in the while loop you are re-reading it: why is that? Can't you do something like:
// Wait for button being released
while (level == LOW) {
delay(100);
}
?
Also don't you want to reassign the btn2_t0 = t1; even when the time was smaller than 700 ms? Like:
t1 = millis();
if (t1 - btn2_t0 < 700) {
btn2_t0 = t1;
return;
}
The behaviour depends on how you built your electronic circuit: is the button-press suppose to make the pin high or low? Be sure about the behaviour is the one you are expecting by either connecting a led and a resistor or using a Voltmeter.
However since your Python code worked I am assuming the electronic is correct and your algorithm too.
Be sure of course you are pressing the button long enough. Add some prints to your code to understand which branches it is executing because when there is electronic involved it is difficult to understand only by the code.
While waiting for news from you, in my opinion is better to do the following: define the callback as: INT_EDGE_BOTH so that it got called when the bottom is pressed and when the button is released. You can keep the time elapsed with a static variable.
void yourCallback()
{
unsigned long ela, t;
int level = digitalRead(BUTTON_2_PIN);
static unsigned long button_pressed_timestamp;
//if button pressed:
if(level==LOW)
{
//start counting
button_pressed_timestamp = millis();
}
else //button released
{
duration = millis()-button_pressed_timestamp;
button_pressed_timestamp = millis(); //just to be sure....
if (duration > 5000) {
printf("Self destruction sequence initiated!\n");
}
else if (duration > 700) {
player_previous();
}
else {
player_next();
}
}
}
I've got a problem with my arduino program. I'm using a RFID reader to scan cards (this part works flawlessly). I want the program to grant access to using some buttons (doesn't matter to be honest). The user who uses a verified card can use the functionalities until he scans a card again. I've deleted some unnecessary parts of the code.
#include <SPI.h>
#include <MFRC522.h>
String read_rfid;
String ok_rfid_1="a3f90f7"; //ID of the verified CARD
const int buzzer=8; //Buzzer
const int redLed=7;
const int greenLed=6;
const int yellowLed=5;
byte access=false; //
void setup() {
Serial.begin(9600); // Initialize serial communications with the PC
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522 card
}
/*
* Helper routine to dump a byte array as hex values to Serial.
*/
void dump_byte_array(byte *buffer, byte bufferSize) {
read_rfid="";
for (byte i = 0; i < bufferSize; i++) {
read_rfid=read_rfid + String(buffer[i], HEX);
}
}
void granted() { } //it lights up the green led
void denied() { } //it lights up the red led
void login() {
if (read_rfid==ok_rfid_1) {
granted();
access=true;
} else {
denied();
}
delay(1000);
}
void logout() {
if (read_rfid==ok_rfid_1 && access==1) {
access=false;
Serial.println("Logout ");
}
}
void loop() {
// Look for new cards
if ( ! mfrc522.PICC_IsNewCardPresent())
return;
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial())
return;
dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
Serial.println(read_rfid);
login();
while(access==true)
{logout();};
}
The logging in part works well, but it logs out automatically. As I observed the problem might be that if(read_rfid==ok_rfid_1 && access==1) is always true, because the read_rfid does not change. Do you have any ideas to solve my dillema?
I want to move my robot a set number of steps and then have it stop. However the loop just seems to run on infinitely. Is there a mistake in the way that I am using void loop() or perhaps in the way that I have written my 'for' loop?
// walkerForward.pde - Two servo walker. Forward.
// (c) Kimmo Karvinen & Tero Karvinen http://BotBook.com
// updated - Joe Saavedra, 2010
#include <Servo.h>
Servo frontServo;
Servo rearServo;
int centerPos = 90;
int frontRightUp = 75;
int frontLeftUp = 120;
int backRightForward = 45;
int backLeftForward = 135;
void moveForward(int steps)
{
for (int x = steps; steps > 0; steps--) {
frontServo.write(centerPos);
rearServo.write(centerPos);
delay(100);
frontServo.write(frontRightUp);
rearServo.write(backLeftForward);
delay(100);
frontServo.write(centerPos);
rearServo.write(centerPos);
delay(100);
frontServo.write(frontLeftUp);
rearServo.write(backRightForward);
delay(100);
}
}
void setup()
{
frontServo.attach(2);
rearServo.attach(3);
}
void loop()
{
moveForward(5);
}
the loop() function is executed within an infinite loop (if you check the main cpp file that ships with the Arduino IDE, you'll see something like this:
int main()
{
setup();
for (;;) {
loop();
}
return 0;
}
So either put the call to your moveForward() function to setup() and make loop() an empty function, or call exit(0); from within loop() after moveForward(). The first approach looks like this:
void setup()
{
frontServo.attach(2);
rearServo.attach(3);
moveForward(5);
}
void loop()
{
}
And the second one looks like this:
void setup()
{
frontServo.attach(2);
rearServo.attach(3);
}
void loop()
{
moveForward(5);
exit(0);
}
Since you probably will want to eventually do more than move the robot just 5 steps, I'd suggest using a variable flag to hold the robot state. It only executes the movement routine when the flag has been set to true.
If you are using serial, when a move command is received (and the number of steps, direction perhaps?) you set the flag to true and then issue the move command. If you are using sensors or buttons, the same logic applies.
You will need some logic to handle an incoming movement command while a movement is occurring (though with your tight movement loop you actually won't be able to respond to incoming commands unless you use interrupts - but you want to consider this sort of thing if you are planning to build out a full movement bit of firmware).
boolean shouldMove;
void setup()
{
shouldMove = true;//set the flag
}
void loop()
{
if (shouldMove){
moveForward(5);
}
}
void moveForward(int steps)
{
shouldMove = false; //clear the flag
for (int x = steps; steps > 0; steps--) {
// tight loop controlling movement
}
}
}