How to fix an always HIGH Input - python

I'm trying that my ESP-32 sends a high output to the Raspberry pi 3 B +. I already tried using different pins but the result is always the same. The Raspberry things he always gets a high input. The goal is, that the raspberry should take a photo when the esp 32 sends a high output.
Before you ask how the ESP should know when he should send an output. Well, it is when he detects an object.
Here you can see my python code
import time
import os # import the time
from picamera import PiCamera # import image from the camera into the Raspberry
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM) # define pins
GPIO.setup(11, GPIO.IN) # setup pin 18 as input
if __name__=='__main__':
#Variable
cam = Picamera() # makes the variable cam
while True:
if(GPIO.input(11) == GPIO.HIGH):
#Define how newimagen is made of (Variable) # make the variable fname which give us the date and Time
os.chdir('/home/pi/Desktop/image/') # Define where we are working now
images = [i for i in os.listdir(os.getcwd()) if i.lower().startswith('image')] # define what images is :
# os.listdir returns a list containing of the entries in the directory os.getcwd...
# os.getcwd returns the current working directory of a process
if images:
newest = max(images, key=os.path.getmtime) # max() is a method that returns the largest item of sth
# os.path.getmtime return the time of last modification
else:
newest = 'image0.jpg'
number = int(''.join([i for i in newest if i.isdigit()])) #number is the number of the newest image : image1 --> number = 1. This method look up if there is an image and which number it has
newimagen = 'image'+str(number+1)+'.jpg' # newimagen is the variable that decide which image it will be(image1 or image2...)
#Camera Code changing
cam.resolution = (2592,1944) # method to change the resoltuion
#Main Code
cam.capture('/home/pi/Desktop/image/'+newimagen) # method that take a photo and then save it on the local desktop as the name of newimagen
Here my Arduino Code
// Define SensorS pins
#define trigPin 15
#define echoPin 2
//Define SensorXL pins
#define trigPinXL 14
#define echoPinXL 13
//Define Raspberry Pin
#define RaspiPin 26
//Define Motor pins
#define motorIn3 16 //Input 3
#define motorIn1 17 //Input 1
#define motorIn4 18 //Input 4
#define motorIn2 19 //Input 2
// Defines variables
long duration;
int distance;
// Define ActivateDistance
const int activateDistance = 40;
const int activateDistance2 =40;
void setup()
{
// Sets the trigPin as an Output
pinMode(trigPin, OUTPUT);
pinMode(trigPinXL, OUTPUT);
// Sets the echoPin as an Input
pinMode(echoPin, INPUT);
pinMode(echoPinXL, INPUT);
// sets the Motorpins as outputs:
pinMode(motorIn1, OUTPUT);
pinMode(motorIn2, OUTPUT);
pinMode(motorIn3, OUTPUT);
pinMode(motorIn4, OUTPUT);
//Sets Raspberry Pin as output
pinMode(RaspiPin, OUTPUT);
// Starts the serial communication
Serial.begin(9600);
}
void stop()
{
// stop motor without duration
Serial.println("STOP");
digitalWrite(motorIn1, LOW);
digitalWrite(motorIn2, LOW);
digitalWrite(motorIn3, LOW);
digitalWrite(motorIn4, LOW);
}
void left(int duration)
{
//Motor goes to left
Serial.println("LEFT");
digitalWrite(motorIn1, LOW);
digitalWrite(motorIn2, HIGH);
digitalWrite(motorIn3, HIGH);
digitalWrite(motorIn4, LOW);
delay(duration);
stop();
}
void right(int duration)
{
//Motor goes to left
Serial.println("RIGHT");
digitalWrite(motorIn1, HIGH);
digitalWrite(motorIn2, LOW);
digitalWrite(motorIn3, LOW);
digitalWrite(motorIn4, HIGH);
delay(duration);
stop();
}
void forward(int duration)
{
//Motor goes forward
Serial.println("FORWARD");
digitalWrite(motorIn2, HIGH);
digitalWrite(motorIn4, HIGH);
digitalWrite(motorIn3, LOW);
digitalWrite(motorIn1, LOW);
delay(duration);
stop();
}
long get_distance(void)
{
//get distance from sensor
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2;
return distance;
}
long get_distanceXL(void)
{
//get distance from sensor
// Clears the trigPin
digitalWrite(trigPinXL, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPinXL, HIGH);
delayMicroseconds(10);
digitalWrite(trigPinXL, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPinXL, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2;
return distance;
}
int turn = 0;
void loop()
{
// check sensor
if (get_distance() <= activateDistance)
{
Serial.println("Found an Obstacle!!!");
// go right for 1 second
right(1000);
while(turn<4)
{
//turn on the Raspberry Pin
digitalWrite(RaspiPin, HIGH);
if(get_distanceXL()>activateDistance2)
{
//go left for 1 second
left(1000);
forward(1500);
turn = turn + 1;
}
else
//go forward for 1 second
forward(1000);
}
//turn off the Raspberry Pin
digitalWrite(RaspiPin, LOW);
}
else
// go forward for 1 second
forward(1000);
}
I've opened my Terminal and saw this issue. I am not sure if this will help with my problem :
mmal: mmal_vc_port_enable: failed to enable port vc.null_sink:in:0(OPQV): ENOSPC
mmal: mmal_port_enable: failed to enable connected port (vc.null_sink:in:0(OPQV))0x1d13d20 (ENOSPC)
mmal: mmal_connection_enable: output port couldn't be enabled
Traceback (most recent call last):
File "/home/pi/Desktop/camera.py", line 12, in <module>
cam = PiCamera() # makes the variable cam
File "/usr/lib/python2.7/dist-packages/picamera/camera.py", line 433, in __init__
self._init_preview()
File "/usr/lib/python2.7/dist-packages/picamera/camera.py", line 513, in _init_preview
self, self._camera.outputs[self.CAMERA_PREVIEW_PORT])
File "/usr/lib/python2.7/dist-packages/picamera/renderers.py", line 558, in __init__
self.renderer.inputs[0].connect(source).enable()
File "/usr/lib/python2.7/dist-packages/picamera/mmalobj.py", line 2212, in enable
prefix="Failed to enable connection")
File "/usr/lib/python2.7/dist-packages/picamera/exc.py", line 184, in mmal_check
raise PiCameraMMALError(status, prefix)
picamera.exc.PiCameraMMALError: Failed to enable connection: Out of resources

There is a small error in your logic:
if(GPIO.input(11) == GPIO.HIGH)
Instead, you should be checking if there is any input on your pin 11, like
if(GPIO.input(11)){
// the rest f you logic
}
Which will return True or False, based on if there is any input (current) going trough PIN 11.
GPIO.HIGH is supposed to to set a pin to HIGH, not to check if the pin is getting input or no.

Related

Arduino/Python Serial communication

I want to send data from python to may Arduino Mega via serial output. The Arduino's RX Led blinks, when I run the Python script. However, the Serial.available() = false. This is just an example code. The real project is building a speedometer for sim racing games (using UDP data). Any idea why it isn't working?
Here is the code:
Python:
import time
import serial
port = "COM3"
Arduino = serial.Serial(port ,9600, timeout=1);
i = 0
while i<= 9999 :
time.sleep(1/10)
i+=1
print(i)
Arduino.write(i)
Arduino:
#include <Arduino.h>
#include <TM1637Display.h>
#define CLK 2
#define DIO 3
int i=0;
int Number;
TM1637Display display(CLK, DIO);
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(9600);
display.setBrightness(0x0f);
display.showNumberDec(9999);
delay(3000);
}
void loop() {
Number= Serial.read();
if (Serial.available()>0){
display.setBrightness(0x0f);
display.showNumberDec(Number);
}
if (Serial.available() == false){
display.setBrightness(0x0f);
display.showNumberDec(0000);
}
}
This is how it works. Big thanks to csongoose from reddit who helped me a lot. Also thanks to all your replies on this.
Python:
import time
import serial
port = "COM3"
Arduino = serial.Serial(port ,9600, timeout=1);
i = 0
while i<= 9999 :
time.sleep(1)
i+=1
print(i)
#converts int i to string b
b = "%s" %i
Arduino.write(bytes(b, 'utf-8'))
#the Arduino waits for this and can seperate the numbers
Arduino.write(b'\n')
Arduino:
#include <Arduino.h>
#include <TM1637Display.h>
#define CLK 2
#define DIO 3
#define D1 5
#define D2 7
int Number;
String b;
//i am using a 7-digit display to show the numbers
TM1637Display display(CLK, DIO);
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
pinMode(D1 ,OUTPUT);
pinMode(D2 ,OUTPUT);
Serial.begin(9600);
}
void loop() {
if (Serial.available()>0){
//looks for new numbers, which are sperated with '\n'
b = Serial.readStringUntil('\n');
//converts string b to integer Number
Number = b.toInt();
display.setBrightness(0x0f);
display.showNumberDec(Number);
//delay equals the same rate as python sends data
delay(1000);
}
//this indicates if the data is available and if the Arduino has rebooted
//you need to wait for it and then start your Python stream
if (Serial.available() == 0){
digitalWrite( D1, HIGH);}
else digitalWrite(D1, LOW);
if (Number != 0){
digitalWrite( D2, HIGH);}
else digitalWrite(D2, LOW);
}

Read multiple arduino's using a Raspberry Pi 3 through USB

I have 3 arduino's that have RC522 rfid readers attached to them. They each have their own power supplies and they are connected to a raspberry pi 3 via the usb ports. I am getting really inconsistent results when running the reader in python. It does appear all 3 are reading but the loop does some weird things. Sometimes the chip code keeps repeating after the chip is removed and other times it works properly. There does not appear to be any consistency with which arduino is behaving oddly either.
Any help would be greatly appreciated!!!
Here is the arduino code (The same code was copied to each arduino with the exception of the initial println that indicates which arduino is connected).
#include <SPI.h>
#include <MFRC522.h>
#define RST_PIN 5 // Configurable, see typical pin layout above
#define SS_PIN 53 // Configurable, see typical pin layout above
#define MOSI_PIN 51
#define MISO_PIN 50
#define SCK_PIN 52
MFRC522 rfid(SS_PIN, RST_PIN); // Instance of the class
MFRC522::MIFARE_Key key;
String read_rfid;
void setup() {
Serial.begin(9600);
SPI.begin(); // Init SPI bus
rfid.PCD_Init(); // Init MFRC522
for (byte i = 0; i < 6; i++) {
key.keyByte[i] = 0xFF;
}
Serial.println(F("The Toy Maker's Sanctuary RDIF Reader 1 Online."));
//Serial.println(F("Using the following key:"));
//printHex(key.keyByte, MFRC522::MF_KEY_SIZE);
}
void loop() {
// Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
if ( ! rfid.PICC_IsNewCardPresent())
return;
// Select one of the cards
if ( ! rfid.PICC_ReadCardSerial())
return;
dump_byte_array(rfid.uid.uidByte, rfid.uid.size);
Serial.println(read_rfid);
}
/*
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);
}
}
Here is the python code
import serial
ser0=serial.Serial("/dev/ttyACM0", 9600, timeout=1)
ser1=serial.Serial("/dev/ttyACM1", 9600, timeout=1)
ser2=serial.Serial("/dev/ttyACM2", 9600, timeout=1)
ser0.baudrate=9600
ser1.baudrate=9600
ser2.baudrate=9600
read_ser0=""
read_ser1=""
read_ser2=""
while True:
read_ser0=ser0.readline()
print("0: ",read_ser0)
read_ser1=ser1.readline()
print("1: ",read_ser1)
read_ser2=ser2.readline()
print("2: ",read_ser2)
read_ser0=""
read_ser1=""
read_ser2=""

Back and Forth Communication Issue with Python and Arduino

I am developing a code that is suppose to take data from a load cell and based on that data it should control a motor. If the load cell reads a specific value the motor should rotate one direction, if it reads a different value it should go in the other direction. Right now if I apply a load to the sensor the motor will go in one direction, when the load is removed the motor will not go the other way. Instead it continues to go in the wrong direction. I am also having python save the data from the load cell to a csv file and because of that I have noticed that the load cell value stays at a high number like 117 newtons even when the force from the load cell is removed. Before having the communication between arduino and python the output of the sensor was spot on. I have read a little on duplexing and was thinking maybe there in lies my problem. Any help on why my python force value is wrong now would be great.
I have tried a different format to making my arduino code. Arduino Code 2 works, better, I can get the motor to respond to the inputs on the load cell, however as I print the data coming into python it does get a little screwed up. This does not affect my motor surprisingly though. I intend on keeping this incoming data for future use and was hoping that it could be cleaned up. For example lets say that I have 5 newtons of force on there it will display 5 newtons for a few seconds then it will spike to a random number for a couple instances then back to normal.
Python
import serial
import csv
import time
from time import localtime, strftime
import warnings
import serial.tools.list_ports
__author__ = 'Matt Munn'
arduino_ports = [
p.device
for p in serial.tools.list_ports.comports()
if 'Arduino' in p.description
]
if not arduino_ports:
raise IOError("No Arduino found - is it plugged in? If so, restart computer.")
if len(arduino_ports) > 1:
warnings.warn('Multiple Arduinos found - using the first')
Arduino = serial.Serial(arduino_ports[0],9600,timeout=1)
time.sleep(2)
start_time=time.time()
Force = []
Actuator_Signal=[]
outputFileName = "Cycle_Pull_Test_#.csv"
outputFileName = outputFileName.replace("#", strftime("%Y-%m-%d_%H %M %S", localtime()))
with open(outputFileName, 'w',newline='') as outfile:
outfileWrite = csv.writer(outfile)
while True:
while (Arduino.inWaiting()==0):
pass
try:
data = Arduino.readline()
dataarray = data.decode().rstrip().split(',')
Force = round(float(dataarray[0]),3)
print (Force)
if Force < 50:
Arduino.write(b'u')
print ('up')
else:
Arduino.write(b'd')
print('down')
except (KeyboardInterrupt, SystemExit,IndexError,ValueError):
pass
outfileWrite.writerow([Force,"N"])
Arduino
#include <HX711_ADC.h>
#include "CytronMotorDriver.h"
// Configure the motor driver.
CytronMD motor(PWM_DIR, 3, 2); // PWM = Pin 3, DIR = Pin 2.
int up = HIGH;
int down = LOW;
int dstate = up;
int python_direction = 0;
float interval = 12000;
float pretime= 0;
float curtime = 0;
// LOAD CELL
//HX711 constructor (dout pin, sck pin)
HX711_ADC LoadCell(11, 12);
float force;
float calforce;
float newtons;
// The setup routine runs once when you press reset.
void setup() {
Serial.begin(9600);
LoadCell.begin();
LoadCell.start(2000); // tare preciscion can be improved by adding a few seconds of stabilising time
LoadCell.setCalFactor(100); // user set calibration factor (float)
}
// The loop routine runs over and over again forever.
void loop() {
if (Serial.available()>0){
python_direction = Serial.read();
Serial.print (python_direction);
Serial.print (",");
}
LoadCell.update();
force = LoadCell.getData();
force = (force/285); // Force in (N) // 285 is conversion factor
calforce = (-1.0389*force)+0.0181, // This is in lbs
newtons = 4.45*calforce;
receive from serial terminal for tare
if (Serial.available() > 0) {
char inByte = Serial.read();
if (inByte == 't') LoadCell.tareNoDelay();
}
unsigned long curtime = millis();
if (python_direction == 'u'){
motor.setSpeed(255); // Run forward at full speed.
}
if (python_direction == 0){
motor.setSpeed(0); // Stop motor.
}
if (python_direction == 'd'){
motor.setSpeed(-255); // Run backward at full speed.
}
Serial.println(newtons);
}
Arduino 2
#include <HX711_ADC.h> // HX711 Library
#include "CytronMotorDriver.h"
// Configure the motor driver.
CytronMD motor(PWM_DIR, 3, 2); // PWM = Pin 3, DIR = Pin 2.
int up = HIGH;
int down = LOW;
int dstate = up;
int python_direction = 0;
float interval = 12000;
float pretime= 0;
float curtime = 0;
HX711_ADC LoadCell(11, 12);
float force;
float calforce;
float newtons;
void setup() {
Serial.begin(9600);
LoadCell.begin();
LoadCell.start(2000); // tare preciscion can be improved by adding a few seconds of stabilising time
LoadCell.setCalFactor(100.0); // user set calibration factor (float)
}
void loop() {
LoadCell.update();
forceRead();
actuatorControl();
}void forceRead()
{
force = LoadCell.getData();
force = (force/285); // Force in (N) // 285 is conversion factor
calforce = (-1.0389*force)+0.0181, // This is in lbs
newtons = 4.45*calforce;
Serial.println(newtons);
//receive from serial terminal for tare
if (Serial.available() > 0) {
char inByte = Serial.read();
if (inByte == 't') LoadCell.tareNoDelay();
}
}
void actuatorControl(){
if (Serial.available()>0){
python_direction = Serial.read();
Serial.print (python_direction);
Serial.print (",");
}
if (python_direction == 'd'){
motor.setSpeed(255); // Run forward at full speed.
}
if (python_direction == 0){
motor.setSpeed(0); // Stop motor.
}
if (python_direction == 'u'){
motor.setSpeed(-255); // Run backward at full speed.
}
}

Pyserial not getting new value from Arduino

I'm trying to stream the data from an ultrasonic rangefinder on an Arduino to my laptop. I seem to be having an issue with getting the new value from the Arduino. When I launch the Python script it starts printing the data just like I hoped. However this data does not change when I change the distance the sensor sees, it's almost like the serial.readline() is stuck on one of the first values. I'm new to this serial communication stuff so any help is greatly appreciated!
The code is below and for sanity I did check that the sensor is working with the serial monitor in the Arduino IDE.
import numpy
import serial
import time
import sys
import cv2
import pickle
#set up the camera stuff
cap = cv2.VideoCapture(0)
#container for images
images=[]
#container for distances
distances=[]
#first frame number
frame_num=1
#setup the serial connection and pause to establish it
ser = serial.Serial('/dev/cu.usbmodem1421', 9600,timeout=1)
time.sleep(5)
while True:
try:
#grab and image
ret,frame=cap.read()
#grab the distance
distance=ser.readline()
print(distance)
#process the image to a gray and 1241,376
#gray=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
#gray_resized=cv2.resize(gray,(1241,376))
#cv2.imshow("FRAME",gray_resized)
#print(distance)
#images.append([frame_num,gray_resized])
#distances.append([frame_num,distance])
#ser.flush()
except KeyboardInterrupt:
#pickle.dump( images, open( "save.p", "wb" ) )
#pickle.dump( distances, open( "save.p", "wb" ) )
sys.exit()
Arduino code:
// defines pins numbers
const int trigPin = 7;
const int echoPin = 8;
// defines variables
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
delayMicroseconds(50);
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance in CM
distance= duration*0.034/2;
String distance_out=String(distance);
// Prints the distance on the Serial Monitor in CM
Serial.println(distance);
Serial.flush();
//Serial.print("Distance: ");
//Serial.println(distance);
}
Actually, python's serial.readline() is blocking until it get a EOL, so if you do not have lock issue that mean the Arduino is writing in the buffer faster that your python script read it.
You should flush the buffer after reading to ensure (close to) realtime reading with serial.flushInput() or serial.reset_input_buffer() depending of your version

Python Tkinter Slider Widget write Value over I2C

Ok I have been searching for an example for a while now can not seem to find any examples of relaying the tkinter slider values over I2C to Arduino. So far I have not tried to communicate with the Arduino yet. Ill cross that bridge next; for now I just want to figure out how to write the slide widget values and send over I2C.
Here is a simple GUI slider widget in Python 2 with what I believe is the correct setup for I2C communications. Ive updated the Rpi to set up the I2C as well. What I want to do in Arduino is simply read the values 0 to 180 for a servo control. It is important that it just writes values or in some way that can be used for an input. I have other code in the arduino that drives the same servo, if other conditions are met and this would then be ignored.
from Tkinter import*
import RPi.GPIO as GPIO
import time
import smbus
bus = smbus.SMBus=(1)
SLAVE_ADDRESS = 0x04
class App:
def __init__(self, master):
def SendScaleReading(self):
S = scale.get()# Now how do we write this and get the Scale Value and send it??
bus(SLAVE_ADDRESS, ord('S'))#According to an example this should be
#"bus.write_byte(SLAVE_ADDRESS, ord('S'))"
frame = Frame(master)
frame.pack()
scale = Scale(frame, from_=0, to=180, orient=HORIZONTAL, command=SendScaleReading)
scale.grid(row=1, column=1)
root = Tk()
root.wm_title('I2C servo control')
app = App(root)
root.geometry("200x50+0+0")
root.mainloop()
Ok a friend helped me out with and I wasnt too far off. Once I got this far I only a small issue with an IO error. I was getting [Errno 5] IO errors. Make sure you have a ground connected between the Arduino and Pi. When I searched this seemed to be overlooked by the many fixes out there offered. You need SDA, SLA and Gnd all connected.
So anyways here is the code that is working running an arduino i2c blink sketch. This will blink the led on pin 13 faster or slower based on the slider input in from the Rpi over I2C. I am going to try and write this code to control a servo next and if successful I will also post that code.
Rpi / python2 code below:
from Tkinter import*
import RPi.GPIO as GPIO
import time
import smbus
bus = smbus.SMBus(1)
SLAVE_ADDRESS = 0x28
class App:
def __init__(self, master):
def SendScaleReading(self):
S = scale.get()
print("we have" );
print( S )
bus.write_byte_data(SLAVE_ADDRESS, S, S )
frame = Frame(master)
frame.pack()
scale = Scale(frame, from_=0, to=180, orient=HORIZONTAL, command=SendScaleReading)
scale.grid(row=1, column=1)
root = Tk()
root.wm_title('I2C servo control')
app = App(root)
root.geometry("200x50+0+0")
root.mainloop()
Arduino i2c wire Blink sketch below:
#include <Wire.h>
// unique address for this I2C slave device
#define ADDRESS 0x28
// constants won't change. Used here to
// set pin numbers:
const int ledPin = 13; // the number of the LED pin
// Variables will change:
int ledState = LOW; // ledState used to set the LED
long previousMillis = 0; // will store last time LED was updated
// the follow variables is a long because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
volatile long interval = 1000; // interval at which to blink (milliseconds)
void setup() {
// set the digital pin as output:
pinMode(ledPin, OUTPUT);
Wire.begin(ADDRESS); // join i2c bus with address #4
Wire.onReceive(receiveEvent); // register event
Wire.onRequest(requestEvent); // register the request handler
}
//gets called when I2C read occurs
void requestEvent() {
//any request for data will return 0x14 (random number i picked for testing)
Wire.write( 0x14 );
}
// get called when I2C write occurs
void receiveEvent(int howMany) {
//just going to support 1 byte commands for now
if (howMany >0 ) {
int c = Wire.read();
interval = c * 10;
}
while (Wire.available() > 0 ) {
Wire.read();
}
}
void loop()
{
// here is where you'd put code that needs to be running all the time.
// check to see if it's time to blink the LED; that is, if the
// difference between the current time and last time you blinked
// the LED is bigger than the interval at which you want to
// blink the LED.
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
if (ledState == LOW)
ledState = HIGH;
else
ledState = LOW;
// set the LED with the ledState of the variable:
digitalWrite(ledPin, ledState);
}
}
Ok well the servo code ended up being rather simple. Im sure it can be cleaned up so anyone with the know how please feel free to make improvements.
Arduino I2C Driven Servo Sketch is below:
#include <Wire.h>
#include <Servo.h>
// unique address for this I2C slave device
#define ADDRESS 0x28
Servo myservo;
int pos = 0;
void setup() {
myservo.attach(9);
Wire.begin(ADDRESS); // join i2c bus with address #4
Wire.onReceive(receiveEvent); // register event
Wire.onRequest(requestEvent); // register the request handler
}
//gets called when I2C read occurs
void requestEvent() {
//any request for data will return 0x14 (random number i picked for testing)
Wire.write( 0x14 );
}
// get called when I2C write occurs
void receiveEvent(int Pos) {
int val = Wire.read();
pos = val;
while (Wire.available() > 0 ) {
Wire.read();
}
}
void loop()
{
myservo.write(pos);
delay(15);
}

Categories