I've got a number of 5V Trinkets for a robotics project. At the moment I'm writing proof of concept code running with 2 pots, a servo and i2c connection to a Pi Zero W.
Code: Select all
#include "TinyWireS.h"
#include <avr/power.h>
#include "Servo8Bit.h"
#define I2C_SLAVE_ADDR 0x26 // i2c slave address (38)
Servo8Bit myServo;
int input1 = 2; // 'analogue' pin 2 - AKA digital pin 4. #4
int input2 = 3; // 'analogue' pin 3 - AKA digital pin 4. #3
byte number=0;
byte value=0;
int offset=0;
void setup() {
TinyWireS.begin(I2C_SLAVE_ADDR); // init I2C Slave mode
TinyWireS.onReceive(receiveEvent);
TinyWireS.onRequest(requestEvent);
if (F_CPU == 16000000) {
// we are running at 16MHz
clock_prescale_set(clock_div_1);
}
myServo.attach(1); //attach the servo to pin PB1
myServo.write(0); //rotate to the 0 degree position
}
void loop() {
myServo.write(value); // tell servo to go to position in variable value
TinyWireS_stop_check();
}
void receiveEvent(uint8_t) {
number=TinyWireS.receive(); // "number" not used elsewhere just yet.
}
void requestEvent() {
value = (analogRead(input1)/4);
offset = ((analogRead(input2)-512)/8);
value=value+offset;
TinyWireS.send(value);
myServo.write(value);
}
The pots have soldered connections, yet the analogRead() is returning numbers with a jitter. E.g. 192, 192, *5*, 192, 192, 193, 192.
Is a timer operation conflicting with the analogRead do you think? Any improvements I can make to the code to fix this or do I need to look at moving the servo function to a dedicated controller?
Regards,
Mark