How to fix 'I2C communication between 2 microcontrollers intterupted by an intterupt' - arduino

I'm making a dimmer with my Arduino Nano, This get's values between 0-128 from an ESP8266 controller via I2C. This works fine on the nano until the interrupt (zero cross detection) interrupts this.
I've tried dimming with a potentiometer and this worked perfectly, I've tried doing this without the intterupt (in serial monitor), this worked correctly. I've also tried replacing interrupts and noInterrupts by sei() and cli() with no results. I do sometimes get it working for a moment, but then it looks like this.
63
64
65
66
67
-1
69
-1
72
-1
74
Afterwards it stops working.
Below is my code for the ESP8266 device (This is temporary test code). This only sends Value's to the nano.
#include <Wire.h>
void setup() {
Wire.begin();
}
void loop() {
for (int dimValue = 0; dimValue <= 128; dimValue++)
{
delay(50);
Wire.beginTransmission(8);
Wire.write(dimValue);
Wire.endTransmission();
}
}
Below The code for the Nano responsible for dimming and receiving commands via I2C.
#include <Wire.h>
int AC_LOAD = 8; // Output to Opto Triac pin
int dimming = 128; // Dimming level (0-128) 0 = ON, 128 = OFF
int zeroCross = 3; // zerocross pin
void setup()
{
pinMode(AC_LOAD, OUTPUT);// Set AC Load pin as output
attachInterrupt(digitalPinToInterrupt(3), zero_crosss_int, RISING);
Serial.begin(115200);
Wire.begin(8);
Wire.onReceive(receiveEvent);
}
void zero_crosss_int() //function to be fired at the zero crossing to dim the light
{
int dimtime = (75 * dimming); // For 60Hz =>65
delayMicroseconds(dimtime); // Wait till firing the TRIAC
digitalWrite(AC_LOAD, HIGH); // Fire the TRIAC
delayMicroseconds(10); // triac On propogation delay
// (for 60Hz use 8.33) Some Triacs need a longer period
digitalWrite(AC_LOAD, LOW); // No longer trigger the TRIAC (the next zero crossing will swith it off) TRIAC
}
void loop()
{
}
void receiveEvent() {
noInterrupts();
int x = Wire.read();
dimming = x;
Serial.println(x);
interrupts();
}
The results I should get from the nano should look like this
63
64
65
66
67
68
69
70
71
72
73
74

The problem was that the interrupt handler was busy for too long wich interrupted the I2C receive handling wich overflowed it. Now it's fully working by putting the code from the interrupt in the loop().
#include <Wire.h>
int AC_LOAD = 9; // Output to Opto Triac pin
int dimming = 128; // Dimming level (0-128) 0 = ON, 128 = OFF
int zeroCross = 3; // zerocross pin
boolean triacFire = false;
void setup()
{
pinMode(AC_LOAD, OUTPUT);// Set AC Load pin as output
attachInterrupt(digitalPinToInterrupt(zeroCross), zero_crosss_int, RISING);
Serial.begin(115200);
Wire.begin(8); // join i2c bus with address #8
Wire.onReceive(receiveEvent); // register event
}
void zero_crosss_int() //function to be fired at the zero crossing to dim the light
{
triacFire = true;
}
void loop()
{
if (triacFire == true)
{
int dimtime = (75 * dimming); // For 60Hz =>65
delayMicroseconds(dimtime); // Wait till firing the TRIAC
digitalWrite(AC_LOAD, HIGH); // Fire the TRIAC
delayMicroseconds(10); // triac On propogation delay
// (for 60Hz use 8.33) Some Triacs need a longer period
digitalWrite(AC_LOAD, LOW); // No longer trigger the TRIAC (the next zero crossing will swith it off) TRIAC
triacFire = false;
}
}
void receiveEvent() {
noInterrupts();
byte x = Wire.read(); // receive byte as an byte
dimming = x;
Serial.println(x);
interrupts();
}
Thank you, everyone who helped me with this problem!

Related

Arduino send bad signal to interrupt pin

I have connected coin hopper and coin acceptor to one arduino uno, coin acceptor connected to pin 2, coin hopper to pin 3 - sensor and pin 7 - relay. When coin hopper switch relay, it is executing coininterrupt
for coin hopper I am using this script link
coin acceptor script: link
I need this 2 scripts working on 1 arduino
my code:
#define SENSOR 3
#define RELAY 7
#define ACCEPTOR 2
volatile boolean insert = false;
int pulse=0,count;
char sen;
int temp=0;
unsigned long int timer;
void setup()
{
Serial.begin(9600);
pinMode(SENSOR,INPUT_PULLUP);
pinMode(RELAY,OUTPUT);
sen=digitalRead(SENSOR);
digitalWrite(RELAY, HIGH);
attachInterrupt(digitalPinToInterrupt(ACCEPTOR), coinInterrupt, RISING);
}
void loop()
{
if (insert) {
insert = false;
Serial.println("coin");
delay(1000);
}
if(Serial.available())
{
timer=millis();
// temp is amount to dispense send to arduino
temp=Serial.parseInt();
if(temp>0){
digitalWrite(RELAY,LOW);}
}
sen=(sen<<1)|digitalRead(SENSOR);
// if hopper sensor read drop coin
if(sen==1)
{
timer=millis();
pulse++;
sen&=0x03;
Serial.println("out 1");
//if dispensed coins equal with coins to dispense stop engine
if(pulse==temp)
{
digitalWrite(RELAY,HIGH);
pulse=0;
temp=0;
}
}
// if amount dispensed is not equal with amount to dispense and engine running, stop
if((digitalRead(RELAY)==LOW)&(millis()-timer>2000))
{
digitalWrite(RELAY,HIGH);
pulse=0;
temp=0;
}
}
void coinInterrupt() {
insert = true;
}
I was trying to change pins (arduino uno support interrupts on pin 2 and 3 only) but problem still appears so I guess there is issue in the code
your sketch does not run in this state :
first fix errors :
declare insert as volatile
remove cpulse (not used anywhere)
change 'if()' to (I suppose) 'if (insert) ....'
remove stuff with 'sen' var : simply use if(digitalRead(SENSOR)) or if(!digitalRead(SENSOR))
except if you need to store relay state.
use logical operators like || or && unless you really need bitwise operations
example of result sketch :
#define SENSOR 3
#define RELAY 7
volatile boolean insert = false;
byte amountToDispense = 0;
int pulse = 0;
int temp = 0;
unsigned long int timer;
void setup()
{
Serial.begin(9600);
pinMode(SENSOR, INPUT_PULLUP);
pinMode(RELAY, OUTPUT);
digitalWrite(RELAY, HIGH);
attachInterrupt(digitalPinToInterrupt(2), coinInterrupt, RISING);
}
void loop()
{
if (insert ) {
insert = false;
Serial.println("coin");
delay(1000);
}
if (Serial.available())
{
timer = millis();
temp = Serial.parseInt();
if (temp > 0) {
//amountToDispense = Serial.read() - 48;
digitalWrite(RELAY, LOW);
}
}
if (digitalRead(SENSOR))
{
timer = millis();
pulse++;
Serial.println("out 1");
if (pulse >= temp)
{
digitalWrite(RELAY, HIGH);
pulse = 0;
temp = 0;
}
}
if (!digitalRead(RELAY) && (millis() - timer > 2000))
{
digitalWrite(RELAY, HIGH);
pulse = 0;
temp = 0;
}
}
void coinInterrupt() {
insert = true;
}
What is this supposed to do?
sen=(sen<<1)|digitalRead(SENSOR);
You init sen with digitalRead(SENSOR);
Assuming that pin is LOW when you start the sketch and turns HIGH, sen will become 1.
Next you do sen &= 0x03 so sen is still 1.
Again sen=(sen<<1)|digitalRead(SENSOR); , sen will either be 2 or 3.
Next loop run sen=(sen<<1)|digitalRead(SENSOR); sen is now 4 or 6. and so on...
I don't have time to think about what you want to achieve but this is definitely a problem as you'll only enter if (sen == 1) once and never again.
If this is not sufficient you should probably improve your post as it is unclear what arduino sends bad signal to interrup pin is supposed to mean. That doesn't make sense. Explain the expected behaviour of your program and how it behaves instead. add more comments so it becomes clear what you intend to do with each block of code so we don't have to interpret

Arduino LED control sleep

I want to implement a simple LED controller with an Arduino Uno, that goes to sleep and has different buttons.
Functions of buttons are:
Digital 2: Button for ON OFF
Digital 3: Button for Wake up
Everything works ok, but when it goes to sleep, the LEDs also turn off. I want that after 30 seconds, when Arduino goes to sleep, lights stays on.
Here is my code:
#include <avr/sleep.h>
#define REDPIN 10
#define GREENPIN 11
#define BLUEPIN 9
#define delayTime 20 //za fading cas
unsigned long interval= 30000;
unsigned long previousMillis = 0;
const int ledPin = 12; // the pin that the LED is attached to
const int buttonPin1 = 2; //on off
bool vklop = false;
int bela = 10;
int barva;
int prejsnja_barva = 0;
int buttonPushCounter1 = 0; // counter for the number of button presses
int buttonState1 = 0; // current state of the button
int lastButtonState1 = 0; // previous state of the button
/////////////////////////////////////*SETUP*/////////////////////////////////////////
void setup()
{
pinMode(buttonPin1, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
pinMode(3,INPUT); //because of interrupts PIN digital 3
digitalWrite(3,HIGH);
}
/////////////////////////////////////*LOOP*/////////////////////////////////////////
void loop()
{
unsigned long currentMillis = millis();
if ((currentMillis-previousMillis) > interval) //15s timer
{
previousMillis = currentMillis;
Serial.println("SLEEP!"); // kaj delaj po preteku 5s
delay(50);
sleepSetup(); //sleep mode
}
else
{
buttonState1 = digitalRead(buttonPin1);
/////////////////////////////////////ON/OFF/////////////////////////////////////////
/////////////////////////////////////ON/OFF/////////////////////////////////////////
if (buttonState1 != lastButtonState1) // compare the buttonState to its previous state
{
if (buttonState1 == HIGH) // if the state has changed, increment the counter
{
buttonPushCounter1++; // if the current state is HIGH then the button went from off to on:
Serial.println("on");
Serial.print("number of BUTTON1 pushes: ");
Serial.println(buttonPushCounter1);
digitalWrite(ledPin, HIGH);
if(buttonPushCounter1 % 2 == 0)
{
setColor(bela, bela, bela);
vklop = true;
barva = 13;
}
else
{
setColor(0, 0, 0);
vklop = false;
}
}
else // if the current state is LOW then the button went from on to off:
{
Serial.println("off");
digitalWrite(ledPin, LOW);
}
delay(50); // Delay a little bit to avoid bouncing
}
lastButtonState1 = buttonState1; // save the current state as the last state, for next time through the loop
}
}
/////////////////////////////////functions/////////////////////////////////////////////
/////////////////////////////////functions/////////////////////////////////////////////
/////////////////////////////////functions/////////////////////////////////////////////
void setColor(int red, int green, int blue)
{
analogWrite(REDPIN, red);
analogWrite(GREENPIN, green);
analogWrite(BLUEPIN, blue);
}
void sleepSetup(void)
{
sleep_enable(); // Set sleep enable (SE) bit:
attachInterrupt(1, pinInterrupt, LOW); // Set pin 2 as interrupt and attach handler:
set_sleep_mode(SLEEP_MODE_PWR_DOWN); // define our preferred sleep mode:
digitalWrite(13,LOW);
sleep_cpu();
Serial.println("Just woke up!"); //OD TU SE NADALJUJE PO PRITISKU TIPKE
digitalWrite(13,HIGH);
}
void pinInterrupt() //ISR
{
sleep_disable();
detachInterrupt(0);
}
You're using AVR's Power Down sleep mode. In this mode all timers are turned off to save power.
No timers -> no PWM -> no analogue output -> no PWM driven LEDs
To keep the LED on use another sleep mode.
See
http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf for details.
But to be honest I am not quite sure if this makes any sense. If you're driving an LED through 3 outputs the power you can save by putting the MCU into sleep is maybe a few percent.
And as sleep stops the CPU and hence your program you won't be able to have the LEDs turn off after 30s.
Why not just wait 30s befor going to sleep? The alternative would be some external timing circuitry that would also consume power. So I guess having a few milliamps more for 30 seconds is still a better alternative.

Control 2 servo motors with 2 buttons Arduino

I'm working on another school project where I'm trying to make an obstacle course (model size). For this project I'm using 2 servo motors, which I want to control with 2 different buttons. So 1 button is connected to 1 servo motor and the other one is connected to the other servo. I'm actually struggling to get both buttons to work with the servo motors.
When I attach 1 button and 1 servo motor everything works exactly the way I want. I press the button, the servo motor moves 90 degrees and after 5 seconds it moves back.
The code:
#include <Servo.h>
Servo myservo;
const int servoPin = D8; // Servo pin
const int buttonPin = D7; // Pushbutton pin
void setup() {
myservo.attach(servoPin);
pinMode(buttonPin, INPUT);
}//setup
void loop() {
if (digitalRead(buttonPin) == HIGH) {
myservo.write(180);
delay(50); // waits 50ms to reach the position
delay(15000);//15 seconden wachten
myservo.write(0);
delay(50); // waits 50ms to reach the position
}
}//loop
However I read on a forum that when you want to use more then one servo motor, you have to write the code differently. You have to include servo motors like this:
#include <Servo.h>
Servo myservoa, myservob;
When I changed the code everything stopped working and I don't really understand what I'm doing wrong here. I want the servo motors to work AT THE SAME TIME, with 2 different buttons.
The new code:
#include <Servo.h>
Servo myservoa, myservob;
const int servoPin1 = D8; // Servo pin
const int servoPin2 = D6; // Servo pin
const int buttonPin1 = D7; // Pushbutton pin
const int buttonPin2 = D5; // Pushbutton pin
void setup() {
myservoa.attach(servoPin1);
myservob.attach(servoPin2);
pinMode(buttonPin1, INPUT);
pinMode(buttonPin2, INPUT);
}//setup
void loop() {
if (digitalRead(buttonPin1) == HIGH) {
myservoa.write(90);
delay(50); // waits 50ms to reach the position
delay(5000);// 5 seconden wachten
myservoa.write(0);
delay(50); // waits 50ms to reach the position
}
if (digitalRead(buttonPin2) == HIGH) {
myservob.write(90);
delay(50); // waits 50ms to reach the position
delay(5000);// 5 seconden wachten
myservob.write(0);
delay(50); // waits 50ms to reach the position
}
}//loop
I hope somebody can help me out!
EDIT:
So i found out that 2 servo motors actually was to much for my NodeMCU. The code in the comments worked fine tho! Now I'm trying to combine the servo motor with a small vibration motor. The 2 sensors work well together but I can't get the vibration motor to work properly.
I want the vibration motor to vibrate for 5 seconds after I pressed the button. After 5 seconds it has to stop automatically. With the code the vibration motor only vibrates when I press the button. When the button isn't pressed, the vibration motor stops directly.
Code:
#include <Servo.h>
Servo myservo;
const int servoPin = D8; // Servo pin
const int vibratiePin = D3; // Servo pin
const int buttonPin1 = D6; // Pushbutton pin
const int buttonPin2 = D5; // Pushbutton Pin
unsigned long stopA = 0;
unsigned long stopB = 0;
bool controlA = false;
bool controlB = false;
void setup() {
pinMode(buttonPin1, INPUT);
pinMode(buttonPin2, INPUT);
myservo.attach(servoPin);
pinMode(vibratiePin, OUTPUT);
}//setup
void loop() {
unsigned long now = millis();
if(controlA && stopA < now) {
myservo.write(0);
controlA = false;
} else if (!controlA && digitalRead(buttonPin1) == HIGH) {
controlA = true;
myservo.write(90);
stopA = millis() + 5000;
}
if(controlB && stopB < now) {
digitalWrite(vibratiePin, LOW);
controlB = false;
stopB = millis() + 5000;
} else if (!controlB && digitalRead(buttonPin2) == HIGH) {
controlB = true;
digitalWrite(vibratiePin, HIGH);
}
stopB = now;
}
I hope somebody can see the problem here because I don't understand what I'm doing wrong.
Your problem is that you are sleeping the code at each on if statement:
if (digitalRead(buttonPin1) == HIGH) {
...
delay(5000);// the code is blocked for 5 seconds here
...
}
So if the buttonPin1 is HIGH the code after that block will run just after 5100 milliseconds after (at least).
Indeed you shouldn't use longs delays like that inside the loop. The reason is what you see: while the code is stopped the motors are still running and it is a real dangerous scenario for real applications.
The solution is: don't sleep! There are several ways to do it. One of them is use a program variable to control the state of each of motors and another one to set the time limit to run the motor:
unsigned long stopA = 0;
unsigned long stopB = 0;
bool controlA = false;
bool controlB = false;
void loop() {
unsigned long now = mills();
if(controlA && stopA < now) {
myservoa.write(0);
controlA = false;
} else if (!controlA && digitalRead(buttonPin1) == HIGH) {
controlA = true;
myservoa.write(90);
stopA = mills() + 5050;
}
//similar to motor b
//...
}
This way the code never be blocked into a sleeping command and loop can perform other actions while each motor is running.

Arduino Interrupt misbehaving

I'm having some problems with some C code I'm writing for an arduino project. The goal is to digitize a large quantity of analog signals with external multiplexed ADCs, then load these digital values into an external shift register and shift them into the Arduino using SPI.To test my code I only have one ADC multiplexing 4 signals.
The interrupt pin (20) is connected to a comparator circuit which looks at the raw analog signal and pulls the pin high when the voltage is 1V or higher. When the ISR is called it will disable global interrupts "noInterrupts()" set an event flag, detach pin 20 from the interrupt handler, enable global interrupts "interrupts()" and finally return to where it left off.
I'm facing a couple issues, first the ISR is called once fine, a second time fine but after the second ISR call it is not called again untill, which is my seconds issue, the interrupt pin goes low. As per the AttachInterupt() function the ISR should only be called when pin 20 is high. This can be seen in the first and second picture I have attached. Another thing I notice is that the duration that the interrupt pin is high has no effect on whether a 3rd ISR is called.
I'm not sure if this is an issue with my understanding of the interrupt-handling of the Arduino, or a code screw up resulting in a stack overflow or something like that.
// the sensor communicates using SPI, so include the library:
#include <SPI.h>
//Constants
#define RD 41 //pin 41 conneced to read pin
#define INT1 37 //pin 37 connecte to interrupt 1
#define CLK_INH 53 //pin 53 connected to clk inhibit
#define LD 40 //pin 40 connected to load pin
#define INPUT_MAX 3 //input selector limit (Zero Indexed)
#define SENSORS 3 //how many sensors are used (Zero Indexed)
#define DATA_DUMP 38 //pin 29 controlls the data dump deature
#define BYTE_LEN 1 //number of ADC used
#define DEBUG1 17
#define DEBUG2 16
//Controls
unsigned char selector = 0; //ACD input selector
volatile byte eventFlag = LOW; //Control Flag, set to True when event occurs
bool lastButtonState = true;
//Counters
unsigned int i = 0; //eventLog[i]: event counter
unsigned int j = 0; //eventLog[i].data[j]: data counter
//Function Delcarations
unsigned char inputSelector (unsigned char my_selector);
void lockAndPop ();
void dataDump ();
void debug (int pin);
bool fallingEdge (bool); //check for a falling edge of a digital read
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void setup() {
// put your setup code here, to run once:
pinMode(RD, OUTPUT); //Read pin, 0 = begin analog conversion (ADC)
pinMode(INT1, INPUT); //Interrupt pin, 0 = conversion complete (ADC)
pinMode(CLK_INH, OUTPUT); //Clock inhibit pin, 1= no change on output (ShiftRegister)
pinMode(LD, OUTPUT); //Shift/Load pin, 1 = data is shifted (ShiftRegister)
pinMode(DATA_DUMP, INPUT);
pinMode(DEBUG1, OUTPUT);
pinMode(DEBUG2, OUTPUT);
DDRA = 0xFF; //Set port A to ouput
SPI.begin();
//SPI.mode1 Clock idel low CLOP = 0, Data sampled on falling edge CPHA = 1
SPI.beginTransaction(SPISettings(5000000, MSBFIRST, SPI_MODE1));
digitalWrite(RD, HIGH); //Stop conversion
digitalWrite(CLK_INH, HIGH); //No change on the output
digitalWrite(LD, LOW); //Load the shift register
digitalWrite(DEBUG1, LOW);
digitalWrite(DEBUG2, LOW);
attachInterrupt(digitalPinToInterrupt(20), pin_ISR, HIGH); //Call pin_ISR when pin20 goes high
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
typedef struct //event structure, containts a timestamp element and an array of 18 data points
{
unsigned long int timeStamp;
unsigned char data[SENSORS];
} Event;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Event eventLog[200]; //an array of structures representing 200 events, once the 200 events have been filled the data will be printed
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void loop() {
if(fallingEdge(digitalRead(DATA_DUMP))){ //If there is falling edge on the data dump button, call the dataDump function
dataDump();
}
debug(DEBUG2);
if(eventFlag) //if the Event flag is set to true by ISR begin the conversion steps
{
debug(DEBUG1);
digitalWrite(RD,LOW); //Start conversion
while(digitalRead(INT1)){} //Wait for conversion to complete
eventLog[i].timeStamp = micros();
for (j=0; j<=SENSORS; j++) {
lockAndPop(); //lock digital value and reset conversion
PORTA = inputSelector(selector); //increment the selector pin
digitalWrite(RD, LOW); //Start new conversion
digitalWrite(CLK_INH, LOW); //Start the data transfer
eventLog[i].data[j] = SPI.transfer(0); //read a single byte from the SPI line
digitalWrite(CLK_INH, HIGH); //Inhibit clock
digitalWrite(LD, LOW);
while(digitalRead(INT1)){} //wait for previous conversion to end
}
i++;
digitalWrite(RD, HIGH);
selector = 0;
if(i>=200){
dataDump(); //if the event log hits 200 before a data dump is request, dump the data
}
eventFlag = LOW;
attachInterrupt(digitalPinToInterrupt(20), pin_ISR, HIGH);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void pin_ISR() {
noInterrupts();
detachInterrupt(digitalPinToInterrupt(20));
eventFlag = HIGH;
interrupts();
return;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
unsigned char inputSelector (unsigned char my_selector){
if(my_selector==INPUT_MAX){ //if the current selector is at the highest value reset to 0
return 0;
}
return my_selector++; //increment the input selector by 1
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void lockAndPop (){
digitalWrite(LD, HIGH); //Lock in digital value
digitalWrite(RD, HIGH); //Reset conversion
return;
}
void dataDump (){
detachInterrupt(digitalPinToInterrupt(20));
char buf[100], *pos = buf; //create a buffer of 100 charaters, anda pointer to the begining of that buffer
char *base = buf; //create a base address to reset the buffer
unsigned int eventCount = i; //how many events occured before dump command was called
unsigned int localCount;
unsigned int localData;
Serial.begin(115200);
Serial.println(i);
for (localCount = 0; localCount<=eventCount; localCount++){
pos += sprintf(pos, "%lu", eventLog[localCount].timeStamp); //sprintf will append the data to the pointer "pos", and return the number of byte append.
for (localData = 0; localData<=SENSORS; localData++){
pos += sprintf(pos, " %d", (unsigned int)(eventLog[localCount].data[localData]));
}
Serial.println(buf);
pos = base;
}
i=0;
j=0;
Serial.end();
attachInterrupt(digitalPinToInterrupt(20), pin_ISR, HIGH);
return;
}
void debug(int pin){
digitalWrite(pin, HIGH);
digitalWrite(pin, LOW);
return;
}
bool fallingEdge (bool currentButtonState){
if(!currentButtonState&&lastButtonState){
lastButtonState = currentButtonState;
return 1;
}
lastButtonState = currentButtonState;
return 0;
}
There is a bit of noise happening on the ISR pin, but this shouldn't matter as I'm disabled that particular pin within the service routine so I wouldn't think this is an issue

continuous rotation servo (arduino) responding to button press

I am trying to make a continous rotation servo move clockwise if button on pin2 is pressed, and counterclockwise if button on pin3 is pressed. I want the servo to keep moving in the direction set according to the button until the button is released. This is the code I have so far (I am new to arduino):
#include <Servo.h>
Servo myservo; // create servo object to control a servo
// CONSTANTS
// PINS
const int crServo = 12; // sets pin 12 as servo
const int buttonPinCW = 2; // sets pin 2 as button; CW => clockwise => FOCUS FAR
const int buttonPinCC = 3; // sets pin 3 as button; CC => counterclockwise => FOCUS NEAR
const int ledPin = 10; // sets pin 10 as LED
// SERVO PROPERTIES
const int crSpeedDefault = 1500; // 1500 is the stay still position, motor should not turn
const int crSpeedCW = 1300; // 1300 turns the motor full speed clockwise
const int crSpeedCC = 1700; // 1700 turns the motor full speed counter-clockwise
const int crStepDefault = 2;
// SET BUTTON STATES
int buttonStateCW = 0; //sets button 1 as off
int buttonStateCC = 0; // sets button 2 as off
void setup()
{
myservo.attach(crServo); // attaches the servo on pin 12 to the servo object
pinMode (buttonPinCW, INPUT); // sets button as input
pinMode (buttonPinCC, INPUT); // sets button as input
pinMode (ledPin, OUTPUT); // sets led as output
myservo.write(crSpeedDefault); // default servo to crSpeedDefault
}
int slowFocusPull(int x){
int result;
result = abs(x - crSpeedDefault) / crStepDefault;
return result;
}
void loop()
{
buttonStateCW = digitalRead(buttonPinCW);
buttonStateCC = digitalRead(buttonPinCC);
// clockwise rotation
if (buttonStateCW == HIGH) {
digitalWrite(ledPin, HIGH);
myservo.write(slowFocusPull(crSpeedCW));
// counterclockwise rotation
} else if (buttonStateCC == HIGH) {
digitalWrite(ledPin, HIGH);
myservo.write(slowFocusPull(crSpeedCC));
} else {
digitalWrite(ledPin, LOW);
}
}
The issue lies in the function slowFocusPull. Basically I just want to be able to adjust the speed with just modifying the constant. Without this function everything works fine.
UPDATE: final loop for reference
void loop()
{
buttonStateCW = digitalRead(buttonPinCW);
buttonStateCC = digitalRead(buttonPinCC);
// clockwise rotation
if (buttonStateCW == HIGH) {
digitalWrite(ledPinR, HIGH);
float speed = crSpeedCW;
Serial.print("CLOCKWISE-ROTATION \n");
for (int i = 0; i < t * 5; i++) {
speed += ((float)crSpeedDefault - speed)/ 10;
Serial.print(speed);
Serial.print("\n");
myservo.write((int)speed);
delay(100);
}
myservo.write(crSpeedCW);
}
else if (buttonStateCC == HIGH) {
digitalWrite(ledPinG, HIGH);
float speed = crSpeedCC;
Serial.print("COUNTER-CLOCKWISE-ROTATION \n");
for (int i = 0; i < t * 5; i++) {
speed += ((float)crSpeedDefault - speed) / 10;
Serial.print(speed);
Serial.print("\n");
myservo.write((int)speed);
delay(100);
}
myservo.write(crSpeedCC);
}
else {
myservo.write(crSpeedDefault);
digitalWrite(ledPinR, LOW);
digitalWrite(ledPinG, LOW); // turn the LED off by making the voltage LOW
}
}
Looks like your project would benefit from using Hardware Interrupts, which asynchronously call functions when events (like button presses) occur (these are perfect for controllers, and remove the overhead of polling).
Try wiring up the two pins and wiring up the buttons to pins 2 and 3 as is shown in this diagram:
Hardware interrupts literally interrupt the code, the uno has two such pins: digital pin 2 and digital pin 3 (this is really useful for robotics, also the mega has 6 such pins!)
here's a skeleton for how your code might want to look
void setup() {
attachInterrupt(0, goClockwise, RISING); //the "0" places arduino uno's interrupt pin 2 (for uno r3)
attachInterrupt(1, goCounterClockwise, RISING); //the "1" places interrupt for arduino uno's pin 3
}
void loop() {
delay(1000); dummy delay, code is handled in interrupt functions
}
void goClockwise () {
//runs when pin 2's button is pressed
//code for making servo go clockwise
}
void goCounterClockwise () {
//code triggered when pin 3's button is pressed
//code for ccw goes here
}
If you have any questions on I'd be happy to work through them with you.
Here's a link to the Arduino ref page for hardware interrupts:
click here to learn more about arduino hardware interrupts

Resources