# Another Segway clone



## mizlplix (May 1, 2011)

While I have most of the systems nailed down, I DO have a couple of grey areas to contend with.

1- Some use twin motor encoders and swear it is the only way to go as far as perfect control goes., most do not and claim it is not necessary. I have no preference. I just want a quality control strategy.

2-The Arduino codes vary from 300 to 900 lines. Both work. But short of implementing each version, is there any way to tell how well they work from just looking at the code? 

3- The newer control masts are a "side leaning" type while the early ones were the "twisting" type. I have seen the hardware and interface for the twist sticks, but I want to use the newer "leaning" version. Does anyone have an idea of how they work? (How do they interface into the electronics?)

Thx, Miz


----------



## Salty9 (Jul 13, 2009)

Miz,

Can't help with the coding but is there any way that blue fairing can be repurposed on your 2-wheeler?


----------



## mizlplix (May 1, 2011)

OOPS! It is in the trash already...

I considered it, but my width was too different and it would look odd.

It was nice though.

Miz


----------



## mizlplix (May 1, 2011)

The start of the control column.

















It gets a 40" tube and a bicycle wedge type neck with a 
straight pair of the new "Broomhandles" for handlebars.









Then the hard part starts when the "Duino", gyro, bearclaw controller and 6 AGM batteries get here. The wiring is easy, it is the coding and debugging that gets me lost.

Miz


----------



## vmrod (Jul 2, 2010)

Nice job so far!

One of these days, if/when I complete my projects, I may start on one too.


----------



## Sparweb (May 24, 2013)

Wow, neat idea.

Do you already have your hands on Arduino control codes for that? Github, maybe?

Where will you get the speed reference? I see you mention encoders below but I don't see anything on those motors. Will you have to modify the motors to attach something?


----------



## JRoque (Mar 9, 2010)

Nice!! Tell us more about the wheelchair. What brand/model did you buy? It looks like the wheels are in the middle (mid-engine ) and are rather large, which seems ideal for this application. $60 is a steal, where did you find that? Any tips on what to look for when buying a power wheelchair for this?

JR


----------



## mizlplix (May 1, 2011)

OK, in order:

*Code:* I have three sets of arduino codes that worked on that owner's machine. But they all still had glitches and never were debugged. PLUS they only really work if you use their gyro and controller.

So, No, I have some starting places for code, but that is going to be my real challenge when I get there.


*Speed reference:* Most of these Seg type scooters only use the reference from a 3 axis gyro with an accelerator function. They have no dedicated speed indicator. But a few do. they run dual encoders. My motors have a stub shaft where I removed the disk brakes. Encoders can easily be installed there if I need to.


*Wheelchairs:* You need a dual motor chair. Some have one motor and a transaxle.....look carefully.

Mine was a Sunrise Quickie G-424. It uses the very common 90 degree gearbox/motor units. Right and left hand to make a pair. (Craigslist) It cost $10,000 in 2002 when new.

The only damage was in the wheel hubs, the aluminum keyways were wobbled out some. I hammer/peened them back down and used new woodruff keys and red locktite. Fixed for life...LOL

Forget using the motor controller boards as they are NOT arduino compatible.

I used a Roboclaw 30 Amp per channel Robot controller. It does 50 Amps per channel for short bursts....(top left)
I used a G-60 Gyro/acellerometer board.(bottom right)








And a "Ruggeduino" built by Rugged circuits.com. It has over everything protection as well as grounding and reverse voltage.(for those OOPS moments.) top right.

I am using 6- 7.5AH SLA batteries for power because I already have a 24 volt charger....2/S, 3/P for 24 VDC and 22.5AH.








The batteries are hung under the platform. I hot glue gunned them together, wired and soldered the connections.









I reused the nice mini Anderson connector from the chair.









I have the belly pan made and needs refinished and installed.
The basic tiller control is made, it needs the centering springs installed.

I am still in the middle of the fab part.

Miz


----------



## mizlplix (May 1, 2011)

Another days progress...

I padded the battery compartment with a thin layer of crumbled rubber matting.
placed the batteries and hot glue gunned them together. Wired them in three series pairs then the three pairs in parallel for a 24VDC/22.5AH pack.
All this is being built upside down, then it will get turned over when done.

Then the cables are brought to the rear and I reused an Anderson connector. (from the wheelchair)
I got to plug in the charger for a cycle. Everything worked like normal.



I added a 70 amp breaker (from the wheelchair) right, a pack disconnect-middle, and the charger port (from the wheelchair) center.









I made the bottom cover from an old aluminum road sign.








I kept adding rubber layers until the batteries clamped tight with the cover alone.

It is not finished obviously, but it looks like this.








No top deck plate on it yet, or electronics...

Miz


----------



## Sparweb (May 24, 2013)

Cool, it looks 90% done now!
(at least that's what you tell the investors, right?)

Have you connected the accel and the 'duino yet?


----------



## mizlplix (May 1, 2011)

No, no electronics are installed as of now.

I just barely got the pack installed and through a charge cycle.

My next task is to make the detent assy for the control tiller. Then the heavy fab is done and I can clean up the interior of all metal shavings before I install any boards.

Miz


----------



## Sparweb (May 24, 2013)

Just kidding about the appearance
Actually, I am afraid that bench-testing and programming the Arduino will take a while - because I often get stuck at that stage! 

My own experience with a similar thing, trying to get an Arduino-based IMU to work, may help. I discovered that the "free" stuff that I could download from sites like github were incomplete. Some also had tantalizing bits of code that is commented-out but suggesting the author was trying to fix a problem. In the IMU's case the direction would break down or precess after a minute or so. I found myself chasing the potential fixes that the author started, but didn't finish, and still getting nowhere (much like re-inventing the triangular wheel). In the end I had to re-write a lot of code.

I'm also curious about the use of the mems gyro versus accelerometers. The accelerometers will be sensitive to their placement in the segway - up in the handle will give a much stronger response than inside the base. A gyro won't be sensitive to that. In fact I'm trying to guess the best placement for the gyro-accel unit, and thinking that as close as possible to the axis of the wheels may be ideal.


----------



## mizlplix (May 1, 2011)

The "present" wisdom has the gyro/accel/mag board almost at the exact axis of the three center lines.

If that is not sensitive enough, I can always move it later.

I plan to get it to balance, then worry about the steering last.

Thx, Miz


----------



## JRoque (Mar 9, 2010)

Hey Miz, we're ready for an update . How's the project coming? I've been diving through eBay and china-made websites looking for motors, wheels, controllers, etc for one of these things. Craigslist wheelchairs are way too expensive in this area - odd because I live in what's probably the largest wheelchair market in the country.

I thought that a self-balancing device like the one you're building would have needed closed-loop motors of some brushless kind since you need to hold them steady. Brushes don't like that and without feedback it might be hard to hold them locked. 

So, do your motors have worm gears or brakes maybe? Or am I over-thinking it since it has been done before?

JR


----------



## mizlplix (May 1, 2011)

Brushed motors are used all the time. Although bldc or induction might be a better choice.

Progress:

Kick stand, bottom battery cover, disconnect switch, charging port, 70amp breaker.












Fenders and top deck(not shown)









The fenders might need some reshaping at a future point. Flat bent on top looks like a farm tractor.....

Four small closures at the sides are next. Then the stick centering mechanism. 
Followed last by the electronics to keep metal out of them.

It had brakes, but they were not safe for this deal. The controller updates 200 times per secondand so acts like a.closed loop system. BTW. The controller has inputs for two encoders if I can not get the accuracy I need.

Miz


----------



## JRoque (Mar 9, 2010)

Hello all. 

Ok Miz, I dove in and got a pair of wheelchair brushed/angle motors and 16" wheels. I'm going to start looking for the encoders next.

Been looking at the controller you're using and it seems good. What control strategy will you be using? I'm kinda puzzled they've cut themselves short in terms of resolution but maybe that's just the geek in me talking. They have:

- Analog mode where 0V = Full reverse, 1V = Stop and 2V = Full forward
- Simple Serial mode where there's 63 discrete values to control speed.
- Packet Command mode (serial) with a range of 0 - 127 for both forward and backwards
- RC mode where there are 500 discrete pulses to control each motor speed.

So, which one are you using? I which they had a wider range on analog but not having that, it looks like RC mode has the best resolution.

JR


----------



## mizlplix (May 1, 2011)

As for the controller, it has like an 80 page manual that you can download and get some really specific answers.

http://downloads.orionrobotics.com/downloads/datasheets/motor_controller_robo_claw_R0402.pdf

As for me, I have read so much my head hurts. I decided, but do not remember just what I decided. (Alcohol was involved) Actually, I am operating one step ahead of my actual work and while I have the electronics pretty well roughed out, some wiring specifics are not as yet. Example: The Duino to the gyro. The mode for the controller.

When it gets to a certain point, most of the builders were using serial or USB communication because it was easy....It is way too slow to do any fancy balancing. After a few face plants, they figured that out and changed over to an packet serial mode with and without encoders.

The robotics shops have encoders, But I know I can get good ones from US Digital also. Just more expensive. But they have infinite options to get a really custom mount solution. (about $140 Ea)


I am going to try no encoders first, because they work on the controller and not in the Duino circuit. They should be an easy add on.

Miz


----------



## JRoque (Mar 9, 2010)

Ok Miz, I'm starting to post too much on your thread with all my questions so please stopped me if you get annoyed.

More questions:

- Don't you want the standing platform to "hang" from the axles rather than being balanced on top? It might be more efficient to hold a position that way. Con: loss of ground clearance

- What is the OD of the back axle on the motor where the brake went? I think I might have found good/cheap optical encoders but most are <3/8".

- I read somewhere that these wheelchair motors have quite a bit of backslash in the gears (expected). Does the Arduino code have provisions to take up the backslash?

- Speaking of Arduino, are there libraries complete and available to read/process the gyro and acc inputs or are you planning to tackle that from scratch?

I promise I'll go away as soon as my parts start arriving 

JR


----------



## mizlplix (May 1, 2011)

You are just helping me think my way through this 
quagmire. I appreciate the help and ideas.

so, in order:



> Don't you want the standing platform to "hang" from the axles rather than being balanced on top?


My MK-1 model did just that, but there were some problems.

The motors caused my footing position to be too narrlow when riding.








It was very nice to balance, but it was not worth 
the footing width loss, OR the other problem, 
where to place the batteries...where they were not 
so ugly? The electronics were going to be mounted 
up side down too.


So, I turned it over: It solved the battery problem 
as well as the foot width.








I gained footing width, a place to put the batteries and some
needed ground clearance. (It had 2- 1/2" before, now it has 7".
It is easy to stand on still and manually balances nicely if you 
place the batteries smart.



> What is the OD of the back axle on the motor where the brake went?


Mine are THE most common motors used in mobility chairs, 
even today. They have 3/8" O.D. shafts with 3/8" protruding. 
(they also have 2 flats)



> I read somewhere that these wheelchair motors have quite a bit of backslash in the gears (expected). Does the Arduino code have provisions to take up the backslash?


In my set up, the Arduino does not have to deal with the
backlash or slack. The gyro tells the Duino to tell the 
controller to move the platform back under the gyro 
to keep balance. (200 times per second)

The Duino just tells the controller to power up the 
motors until the thing gets back in balance, then 
powers back and forth to work like brakes. The 
controller powers up until the gyro tells it, thru
the Duino, that is enough. 

When the system has encoders, they are hooked 
directly to the controller, not the Duino. The 
encoders allow the controller to "see" exactly 
when and how much the motors are moving with
the amount of power it applies. It makes it less 
jerky.(so I am told)

The real problem with backlash or chain slack is 
when in balance...They are constantly jumping 
over the slack or lash, back and forth when 
staying in balance. But, so does a real Segway.
They all have some slack.



> are there libraries complete and available to read/process the gyro and acc inputs or are you planning to tackle that from scratch?


I have 3 sets of code I have gleaned from the "Net".
I will try them seperately and keep the best performing one. 

Even then, ALL of them say the same thing, "My code 
needs some more tweaking".......

So, I plan some tweaking too.

Miz

P.S.:-My short experience tells me that the best motor/gearboxes are coaxial.
It gives foot/deck room, ground clearance and hides the batteries and motors,
while keeping the footing at or below the axle centerline.


----------



## JRoque (Mar 9, 2010)

Excellent post, Miz, thank you. 

Ok so I got 3 US Digital encoders off of eBay for 3/8" shaft. They're only 360 CPR but I think that will be sufficient to keep the motor steady. I offered a little less than was posted and the seller accepted (hint).

I got 4 gyro/acc from eBay also. Only need one but, as the Marines say, 2 is one, 1 is none.



mizlplix said:


> P.S.:-My short experience tells me that the best motor/gearboxes are coaxial.
> It gives foot/deck room, ground clearance and hides the batteries and motors,
> while keeping the footing at or below the axle centerline.


Really?! Doh! I came across a number of those and thought they were less than ideal since that's where my feet would go. I also thought the angle ones had worm gears and could hold a position without power....

I looked into a set of 1kW hub motors on 16" tires from China. Those were about $125ea but for qty 2 they want to send them air and that's another $180ea. You then need controllers, etc and it gets up there. I'll keep that as an option but the wheelchair motors seem like a good compromise overall.

JR


----------



## mizlplix (May 1, 2011)

If money was no problem, I would pick up a pair of bike hub motors.

Some even have the controllers built in them...

They would allow a narrow package and still have a wide foot stance.

I like the 20" bicycle tire because it will give you a low footing below 
the axle centerline and still have enough room for batteries underneath
the platform where they can be covered nicely.

I definitely would use the Arduino Uno as my board of choice as it 
has more things going for it than some of the others.

I am not a fan of the "dead man's" switches under your foot as some
have suggested. Any rough terrain or bumps might cause a simple
interruption of power and an instant face-plant. In the case of a 
thrown rider, the unit will not run away, but will simply remain in 
one spot and balance it"self.

Encoders or no encoders....The jury is still out.

I have decided on using three strain gauges as my steering inputs. 
They are simple-elegant and cheap at $8.00/ea. It takes three. 
One for left, one for right and one as a static test sample for 
temperature compensation.

BTW: the angle gearbox motors will freewheel easily after the 
brake assemblies are removed. The brakes are not needed and 
are actually a potential problem. They require current to hold 
open and they make the motors 3" longer.

The Arduino updates 200 times/second. It acts like it's own 
brake when balancing. Only a downhill slope will cause a 
run-a-way. Even then all you need to do is lean back a little
to "brake". If you tried to use any type of wheel brake, it 
would over ride the balancing and do a face plant.

I am lucky enough to get a volunteer to write me a custom 
code routine and debug the operation of the unit after I 
have it built.

More later, Miz


----------



## JRoque (Mar 9, 2010)

Hi all. 

Boy am I hooked on this thing now. I should be working on my car conversion but this scooter thing is fun, too.

Ok, I got two inline motors as well. Couldn't pass them up at $49 for the pair. I received the 16" wheelchair wheels but the hubs are double-d, not round, and the wrong ID for the motors. The inline motors are 17mm shafts.

I have been scouring the interweb for some nice 20" wheels. I don't like the spokes ones that come for bikes but everything else in that size I've seen is made out of plastic. I agree that 20" would be great and I may have to settle for bicycle spoke wheels.

About steering and balancing, I've been thinking that it might be best to put the sensors up inside the handle. It would give it the most precision for balancing, IMHO. For steering, rather than simply turning if the handle is not centered, it would be best to measure tilt. That way the scooter can ride on the side of an incline and still move in a straight line. Perhaps this is accounted for in the existing code using the base-mounted gyro but it would seem less complicated - and save one sensor - if it's mounted on the handle.

Whoa, a volunteer to write your code? How did that happen?? I'll give the Arduino way a try, this would be my first foray into that. But the boards look like nothing much than an Atmel chip and some peripherals so I can always zap it and use my own code with my favorite compiler.

JR


----------



## mizlplix (May 1, 2011)

"only" 360 pulses/rev.

The one for the Curtis controller is 64 pulses/rev...

Yah, 360 will be great, providing the controller is set up for it.
(The Bearclaw 60 amp controller I bought has direct encoder channels.)

If they went to the Arduino then I would just assume it would be taken care of in the coding.

I DID buy those same encoders/steppers that you did off of Egay. They
should work OK on my motors. (Thanks for the tip)

My motor shafts are only 3/8" stick-out though and the encoders call for 1/2" or more. I can drill/tap the sensor directly on the motor end plate and use the shorter shaft though.

Miz


----------



## JRoque (Mar 9, 2010)

Hi all.


mizlplix said:


> "only" 360 pulses/rev.
> 
> The one for the Curtis controller is 64 pulses/rev...
> 
> Yah, 360 will be great, providing the controller is set up for it.


Yes, a 64 PPR encoder is plenty good to determining speed rate and direction. To hold the motor locked maybe not so much. But I hear you, the DC controller can pretty much do that even without the encoder.



mizlplix said:


> (The Bearclaw 60 amp controller I bought has direct encoder channels.)
> 
> If they went to the Arduino then I would just assume it would be taken care of in the coding.


Yep the DC drive comes with built-in encoder support which was a nice surprise for me. I would definitely let the drive take care of the encoder calcs and not burden the micro with that stuff.



mizlplix said:


> I DID buy those same encoders/steppers that you did off of Egay. They
> should work OK on my motors. (Thanks for the tip)


Your welcome! Let's just hope you did go to "eBay" and not an alternative lifestyle website... not that there's anything wrong with that.



mizlplix said:


> My motor shafts are only 3/8" stick-out though and the encoders call for 1/2" or more. I can drill/tap the sensor directly on the motor end plate and use the shorter shaft though.
> Miz


I noticed that too after removing the brake. I might have problems holding the motor down to drill/tap it. I'll try but might have to cut an adapter on the lathe.

JR


----------



## mizlplix (May 1, 2011)

Some progress:

Fenders, end bulkheads and weather sealant done.








Note holes in deck for cooling fan.

Another pic view:










This is my strain gauge I am using for the steering:








They are really a double unit, in the real delivered form.
Redundancy I guess?

Today, I am working on the coding model balancing robot.








It is nothing but a board connecting the two steppers 
together. Note the encoder on the inside of the far 
stepper.

This way, My software Guru can debug the code and 
make it actually work before loading to the Segway. 
Then only final tuning is needed.


(Software Guru) My oldest son works for a Bio-medical
company that specializes in genetic testing and manipulating
equipment. With a BA in organic chemistry, cellular biology
and Information systems and an MBA, I figure he could do 
it a LOT faster than myself. 


Now I need to find two 4.5" to 5" wheel like things. 
Maybe I need to just cut them out of plywood?? I 
have a lathe to true them and some tool handle rubber
spray for the traction surfaces. They mount with a
simple 1/4" X 3" bolt.

Miz


----------



## mizlplix (May 1, 2011)

The cost of a controller for the steppers made
me buy two of these Robot motor/gearboxes:








That way I can use my Segway controller in the test rig.

The wheels, motors and mounts were around $30.









Debugging and refining the code before installing 
in the Segway will hopefully cut down on the
injuries...LOL

Miz


----------



## JRoque (Mar 9, 2010)

Yeah that's a good move, Miz. I'm not sure the motor that comes with the encoder is a stepper; it looks like a BLDC to me. 

Hopefully the controller will be able to manage the small current readings of that little motor. Why not prop up the real motors and debug with that?

I got my right-angle motors yesterday. These things are huge! 13" long end to end. They take >4A just to start moving and 2.5A no load. I ran one for 5 mins and it started to get warm. The gearbox is 32:1 (!) and shaft speed is 133 RPM. You can do the calc based on your wheel diameter but for a typical wheel, we're talking 5 to 6MPH top speed. I cannot get my head split open at those speeds.

The in-line motors I also have run 1.5A no load, 165 RPM, 17:1 gear ratio and weigh half as much. It's more involved to bolt the inline motors on but I'm going to try them first. With my 16" wheels, we're talking a blistering 8 MPH. Now that's some serious speed.

JR


----------



## mizlplix (May 1, 2011)

Ya, they are husky. These chairs are good for 600lbs......

I agree with you, BLDC. I disassembled one of the motors. They sure are cute though.

My other stuff should be here today. I will get pics of the small robot when done.

Miz


----------



## Ovaltineo (Jul 18, 2013)

JRoque said:


> About steering and balancing, I've been thinking that it might be best to put the sensors up inside the handle. It would give it the most precision for balancing, IMHO. For steering, rather than simply turning if the handle is not centered, it would be best to measure tilt. That way the scooter can ride on the side of an incline and still move in a straight line. Perhaps this is accounted for in the existing code using the base-mounted gyro but it would seem less complicated - and save one sensor - if it's mounted on the handle.
> 
> JR


I think that the further away the sensor is from the pivot point, the more lateral acceleration it will be subject to. You don't want this coz you just want to measure the tilt. It will probably be better to have another sensor on the board for the fore-aft sensing.


----------



## mizlplix (May 1, 2011)

agreed. up on the handle would see a smaller degree of arc than at the axis of rotation / center of the wheel.

closer to the axle is best for a quicker response.

miz


----------



## mac7988 (Jul 19, 2013)

I have built one and is working if you are having trouble please let me know I will help with the code


----------



## mizlplix (May 1, 2011)

Thanks Mac. I will keep you in mind when I get there.

Miz


----------



## JRoque (Mar 9, 2010)

Hi.


Ovaltineo said:


> I think that the further away the sensor is from the pivot point, the more lateral acceleration it will be subject to. You don't want this coz you just want to measure the tilt. It will probably be better to have another sensor on the board for the fore-aft sensing.


Ah! I see, that makes sense. So by the same token, the ideal position of the sensors would be at the intersection of X & Y axes, probably mounted at the end of the handlebar tube where it crosses the wheel axle in the middle/center of the platform. Maybe I should draw it... this is one of those "a pic is worth a thousand words" moments.



mac7988 said:


> I have built one and is working if you are having trouble please let me know I will help with the code


This is Miz's thread and I'm just the resident troll but, do you have a link/pics to your project? I'd love to see the code and construction details.

Welcome to the forum to both of you. Great to see you join to post your helpful comments.

JR


----------



## mizlplix (May 1, 2011)

Feel free to think of this as the Segway thread.

Everyone,s welcome to post their projects here.


I have been into Robotics for many years, but we did not use that distinction. 
The advent of Arduino, Raspberry Pi and some others have really opened up a legitimate Robotics profession.


Up to this point a robot was an arm with a wire welder on it that welded pipelines. No thinking or comping involved.


Now we can do autonomous operations here to fore undreamed of (except by the Sci Fi crowd)


Thx to all of you who respond on this thread.


Miz


----------



## Ovaltineo (Jul 18, 2013)

I've built one too and here are some of my tips:
1. Use MPU-6050 sensor. It's cheap (under $4 in ebay) and very good. It is a single chip sensor with gyro and accelerometer together. Don't forget to change address of one if using two of these.
2. Use an Arduino Mega. You can get a clone (Funduino) for under $20 in ebay and you get multiple serial ports. You also get more memory and IO ports but you won't need them for this project.
3. Use a bluetooth to serial transceiver. You can get one for under $7 in ebay. It's the easiest way to get telemetry data. That's why I recommend the Arduino Mega.
4. Use PWM between Arduino and motor controllers. Digital protocols like I2C and serial are subject to errors from motor spikes. 
5. Make sure it fits easily through a doorway. 
6. Test everything first with a dummy passenger (e.g. sand bags). Make sure to test for heavy-load and stalled conditions (e.g. going up a steep hill). Even with a dummy passenger, wear protection for your legs in case the Segway spins around and hits you (don't ask how I found out ).


----------



## Ovaltineo (Jul 18, 2013)

JRoque said:


> Ah! I see, that makes sense. So by the same token, the ideal position of the sensors would be at the intersection of X & Y axes, probably mounted at the end of the handlebar tube where it crosses the wheel axle in the middle/center of the platform. Maybe I should draw it... this is one of those "a pic is worth a thousand words" moments.
> JR


That's not a bad idea. I think there is another complication with using one sensor -- the value for fore-aft tilt (let's call this X axis) maybe affected by the steering tilt (Y axis) coz the sensor is tilted in two directions. You'll probably need to use X=X/sin(Y) or something like that to compensate.


----------



## mizlplix (May 1, 2011)

Good ideas:

Yes, My scooter is 4" narrower than a standard doorway.

I am only hooking up the one gyro output, the "X" axis, so any other data will not interfere.

Where the "Y" (steering) output from the gyro was to go on the arduino, is where my steering output (from my stick) will go. That it will just bias/modify the balancing signals. This way it will not get "confused" when traversing across slopes.

I have built a small balancing robotic vehicle using all of my components so I can get some code at least working before grafting it all into the Segway, then adding steering inputs.

Yes, PWM to the controller. for sure.

Miz


----------



## Ovaltineo (Jul 18, 2013)

@mac7988,
There is one peculiarity with my clone -- the forward and backward steering are reversed. This means that if I tilt the steering to go right while I'm moving forward, the left wheel speeds up and the right wheel slows down as expected. But if I do this while reversing, the right wheel gains speed and the left wheel slows down. If I change the logic so that the steering is 'correct' in both directions, it gets itself out of balance and will spin very fast. Did you have the same issue?
P.S. I based my code on the MIT Segway code.


----------



## mizlplix (May 1, 2011)

My code is still being written. It is a scratch build.

Your reversing problem needs a line of code stuck in determining "if and when" for forwards and an "If and when" for reverse for the steering inputs or what you describe will result.

The Segway does not know that you reversed travel directions. It needs to be told to watch for it and reverse steering directions too.

Miz


----------



## Ovaltineo (Jul 18, 2013)

Yeah, I did try that but like I said, it gets itself out of balance and will spin very fast if you rock back and forth. It is very stable if I don't make this tiny change. The guys at MIT must have noticed this too and those guys are pretty smart. I think I've got a solution though - I think I need to slowly change the steering delta, but it might make it sluggish though.


----------



## Ovaltineo (Jul 18, 2013)

Here's the part of the code that I'm talking about:

// Compute motor and steer:

board_accel = getBoardAccel();
board_gyro = getBoardGyro();
board_angle = complementaryFilter(board_accel, board_gyro);
speed = computePID(board_angle, board_gyro);
motor = motor + speed;

steer_angle = getSteerAngle();
steer = steer_angle * STEER_MULTIPLER;


// Here's the code that works -- stable

left_motor = motor + steer;
right_motor = motor - steer;

// Here's the alternative code that doesn't work -- unstable

if (board_angle >= 0)
{left_motor = motor + steer;
right_motor = motor - steer;​}
else
{left_motor = motor - steer;
right_motor = motor + steer;​}
​I think the problem with the alternative code is that if the value of "steer" is significant, changing the board angle from + to - (and vise versa) will result in rapid change in the lmotor and rmotor values. This will jerk the board causing it to tilt further and generate an even more rapid response.


----------



## JRoque (Mar 9, 2010)

Hi.


Ovaltineo said:


> I think the problem with the alternative code is that if the value of "steer" is significant, changing the board angle from + to - (and vise versa) will result in rapid change in the lmotor and rmotor values. This will jerk the board causing it to tilt further and generate an even more rapid response.


Does this mean that Steer has no component of Speed in it? If so, will the Seg throw you off if you're doing max speed and then full steer? Not sure where Steer_Multiplier comes from but it seems the right place to include Speed factor.

Also, are these vars signed and, if so, what are their scale values?

JR


----------



## Ovaltineo (Jul 18, 2013)

Angles are in degrees, zero being center for both steering and board tilt. Motor, lmotor, rmotor range from -255 (full reverse) to 255 (full forward). STEER_MULTIPLIER is 3. This means that if I tilt the steering 10 degrees to the right while going forward, it will add 30 to the lmotor and subtract 30 from the rmotor. I find that this constant ratio is fine for both turning in place or moving at full speed. Just like a car, I move the steering less when going fast and more when going slow. It is very natural and used my most Segway codes that I have seen.

Has anyone tried a real Segway? Is the steering ratio constant or speed-sensitive?


----------



## Ovaltineo (Jul 18, 2013)

I just saw a video of a real Segway and noticed that it has the same peculiar steering as my clone. So, looks like I have to live with the steering having an opposite effect when going backwards.
I have attached a photo of my clone. It is lightweight compared to Miz' build. The two boards on the left are my custom-made motor controllers. The board on the right is actually two boards - an Arduino mega on the bottom with a prototype board on top which has the sensor, pots for PID adjustment, and pinout jumpers. The tiny boards to the right of each motor controller are current sensors. The small board on the rightmost is a Bluetooth module.
The motors are 300w scooter motors.


----------



## Sparweb (May 24, 2013)

Something to look forward to when you're done:

http://www.wozcup2012.com/

You'd make quite a splash with your non-segway segway.


----------



## JRoque (Mar 9, 2010)

Nicely done! Any chance you will be posting you code?  What are the dimensions, wheel size?

Hmm.. I have got to rethink my materials selection. I just receive $150 worth of mostly 11 GA (.120" wall) A513 steel square tubing, schedule 40 (.140" wall) pipe and 1" diameter A36 rod for steering base. Plus pillow blocks, 12 GA steel plate... Yikes this thing is going to weigh 300# when I'm done. I may have to break down and buy a bottle of Argon to weld aluminum... if my wimpy 135A welder is even up to that task.

Been poking around with Arduino boards and peripherals. Got a box full of gadgets for Arduino now. I plugged a GY-521 gyro/accl to the microcontroller and loaded some "DPM" code that seems to work ok and shows angles. The code for that alone is rather large so I might dive in and see if I can cook my own, even if I can't use the DPM function of the gyro chip. I'm also leaning back to my comfort zone of using my favorite IDE and compiler. Want to make sure I can debug each of my concussions and know how to avoid a repeat head gash.

Does anyone have a cheap source of 16" to 21" wheels like the Segway X2's? The 16" wheels I have now are double-d hubs vs my 17mm round motor axles and I have no clue how to bore that into a fit.

JR


----------



## Ovaltineo (Jul 18, 2013)

I'll post the code when I get home. The main loop is mostly what I posted before. It is unbelievably simple! I hope you don't have ask for a schematic -- coz I haven't bothered drawing one . The main reason, besides being lazy , is that I don't have schematic drawing tool. I might do it if you can point me to a free one.

I got the inspiration from Petter's Segway clone http://p1r.se/robot/segway/.


----------



## Ovaltineo (Jul 18, 2013)

BTW, I'm happy to start my own thread for fear of taking over Miz' thread. I'm still eagerly awaiting updates from him.


----------



## mizlplix (May 1, 2011)

I stopped and made a small balancing robot to give to my code writer, so he can play with it as he goes along.

I am also slowly building the self-centering spring thingy to keep the control stick in the center and allow only maybe 1/2" travel each way.

I may have to use a slider pot instead of the strain gauges for steering. I can not seem to get the strain gauges to read correctly.

I think it may be the glue I am using....

Miz


----------



## Ovaltineo (Jul 18, 2013)

mizlplix said:


> I may have to use a slider pot instead of the strain gauges for steering. I can not seem to get the strain gauges to read correctly.


For me, a $4 gyro on the steering was the simplest to implement.



mizlplix said:


> I think it may be the glue I am using....


That'll do it !


----------



## JRoque (Mar 9, 2010)

Hi.

I drafted a quick sketch of the future scooter, decision time. Some stats: 

- standing platforms = 16" x 24"
- wheel diameter = 16"
- motor/gear length = 14" (yep)

First, the motors are propped on top the platform. There's ~16" width standing space. The pillow block bearings are under the platform, 1" ID. There's ~2.9" of ground clearance. The back of the motor would never scrape the floor with this config. The standing platform is ~6" off the ground and the center of gravity is below axle. 










Next, the motors on under the platform so there's gobs of space on top for things like rails/fenders, etc. The end of the motor would scrape the floor (after you do) so some sort of bumper would be needed. There's 5.3" of ground clearance and you stand 10" off the ground with center of gravity 2" above the axles. 










What's your take on pro/cons of these designs?

JR


----------



## mizlplix (May 1, 2011)

Hmmmmm.....:

OK, A gyro is fine if you stay on the flat and level always. If you traverse cross slope or even have a one wheel bump, the gyro "thinks" you asked for a turn and WILL give you steering vector change.

Example: If you are going straight and the right tire rolls over a small rock, the gyro will think you asked for a left turn change, and will give you some.

Other than that, it is fine.


Yes, My first generation Segway was like that, board under gearbox.








It was EZ to stand on and balanced well, but my feet were so close together that I felt unstable sideways.


The next generation was better.








Although I was 3" higher, my feet were now shoulders width apart and felt quite stable.

You have found the only down side to these gearbox/motor units.

My perfect Segway would utilize two 20" electric bicycle front drive wheels.
The ones with mag wheels and controllers with encoders inside them. They are $350 /Each. (ouch)

But you could make a killer ride with them. One worthy of a lithium pack.

Miz


----------



## JRoque (Mar 9, 2010)

Hi.


mizlplix said:


> Hmmmmm.....:
> 
> OK, A gyro is fine if you stay on the flat and level always. If you traverse cross slope or even have a one wheel bump, the gyro "thinks" you asked for a turn and WILL give you steering vector change.
> 
> ...


How about if you attach the gyro to the handle? That way the base/wheels can be uneven, etc but the scooter will only turn when you turn the handle. 

Thanks for you comments on the designs. I mocked the two by putting the motors side by side and it seems fine having ~16" between them. I'll have to flare those motors up with something as they can get hot. 

What OD is your handle bar? I'm setting up for a 1" rod plus maybe sch 40 1.5" pipe for the upper handle part. 

On other news, I just bought a pair of 16" Vespa wheels off eBay for $35ea shipped. Now, if I only knew how to machine the hub part, I'd be good. Oh and need some other color paint.

JR


----------



## mizlplix (May 1, 2011)

The neck for my handlebar is off of a 20" bicycle. The bar is 3/4" OD.

The neck fits inside a 3/4" pipe or in this case it is a cut down 48" chrome extension for a ceiling fan. (Home Depot)

The bottom control bar is a piece of 3/4" solid round bar stock, riding in two cooler bearings. (Home Depot)

The bar is $11.00 (off of Amazon).

The handle bar is 41" above the foot standing area.

It leans forward 10" at the bar level.


The Vespa tires/wheels look good.

I would weld together the hub and lug bolt disk flange. I would then true it up in my lathe. Something that big would take a lot of hours to do from billet.

Miz


----------



## Ovaltineo (Jul 18, 2013)

JRoque said:


> Hi.
> 
> How about if you attach the gyro to the handle? That way the base/wheels can be uneven, etc but the scooter will only turn when you turn the handle.
> 
> JR


Miz is right, assuming you keep the handle at 90 degrees relative to the board while going straight and then you traverse a bank or one wheel runs over a rock, it will turn inadvertently. However, in practice, I'm auto-correcting the handle all the time -- like riding a bike, so I don't experience a turn. When going straight, I think I naturally tend to keep the handle perpendicular to the horizon, not the ground below me. So a potentiometer that measures the angle against the board will probably make me turn in a bank. I think it maybe just a case of getting used to your controls.


----------



## Ovaltineo (Jul 18, 2013)

JRoque said:


> Nicely done! Any chance you will be posting you code?  What are the dimensions, wheel size?
> JR


The dimensions of the standing platform are 450mm (17.7 in) width x 400mm (15.7 in) depth. The ground clearance is 3.6 in. The wheels are 12.5 inches in diameter. 

I have cleaned up my code and attached it here. I tried creating a hardware abstraction layer to easily adapt different sensors and motor control. It compiles, but my clone is out-of-action (blew a MOSFET) until I get some parts, so I haven't been able to test it. I'm 95% confident it will work coz all I did is move and rename functions for clarity.

I think the MOSFET blew because I was going down a long steep hill (15 degrees) and braking hard -- now I know why they fit fans on the high-power controllers!


----------



## mizlplix (May 1, 2011)

JR: Looky what I found.
http://www.robotmarketplace.com/products/NPC-PH804.html

3/4" bore with 3/16" keyway. Sounds like it would fit.

Then if you were good with a simple compass, you could make an aluminum disk adapter to bolt your scooter wheels to this hub.

OR a machine shop could put steps on the adapter to get a good register.

Just a thought.

Miz


----------



## Ovaltineo (Jul 18, 2013)

Miz,
I think I may have a simple solution to the gyro/accelerometer steering problem. 

board_y_angle=getBoardYAngle();
steer_angle=getSteerAngle() - board_y_angle;

That will work right?


----------



## mizlplix (May 1, 2011)

With two gyros it sounds good.

Miz


----------



## JRoque (Mar 9, 2010)

Hi all.


Ovaltineo said:


> I have cleaned up my code and attached it here.
> .....
> I think the MOSFET blew because I was going down a long steep hill (15 degrees) and braking hard -- now I know why they fit fans on the high-power controllers!


Thanks! It looks very clean, as you mentioned. I'm going to try your code as-is on the first prototype and see if it goes. Got any video/pics of the build? I'm sweating bullets over the mechanical choices. I'm going to try first with everything on top including the motors, bearings, and maybe even the electronics in a hump in the middle. If that doesn't work I'll follow Miz' lead and flip the platform over.



mizlplix said:


> JR: Looky what I found.
> http://www.robotmarketplace.com/products/NPC-PH804.html
> 
> 3/4" bore with 3/16" keyway. Sounds like it would fit.
> ...


Nice!! That looks like it would bolt right up if I just make a donut and bolt it to the Vespa wheels. Time to dust off my Chinese lathe.

Since I'm nuts about this crap now, I bought yet another set of motors - 3 pairs now and counting. The latest ones are the fastest yet and came with a hub to 4 bolt adapter, similar to Invacare motors on eBay, so that should make it easier to use those motors as well.

JR


----------



## Ovaltineo (Jul 18, 2013)

mizlplix said:


> With two gyros it sounds good.


The $4 MPU6050 that I use has 3 gyros and 3 accelerometers built-in. So you just need one in the steering and one in the board. Compared to the $100+ one would pay for a single gyro a couple of years ago, it is a bargain!


----------



## Ovaltineo (Jul 18, 2013)

JRoque said:


> Thanks! It looks very clean, as you mentioned. I'm going to try your code as-is on the first prototype and see if it goes. Got any video/pics of the build? I'm sweating bullets over the mechanical choices. I'm going to try first with everything on top including the motors, bearings, and maybe even the electronics in a hump in the middle. If that doesn't work I'll follow Miz' lead and flip the platform over.
> 
> 
> Since I'm nuts about this crap now, I bought yet another set of motors - 3 pairs now and counting. The latest ones are the fastest yet and came with a hub to 4 bolt adapter
> JR


I'll upload some more pics later. The biggest problem with my lightweight design is that it doesn't have much torque, so will struggle with inclines greater than 13 degrees. It is fast on flat though (I haven't been brave enough to test it to the limit but it is probably greater than 12 mph). 

What motor controller are you using? There are different modes of PWM so the motor routine might need some change.

You are lucky those motors are cheap in the US. They cost at least $300 here in Australia.


----------



## JRoque (Mar 9, 2010)

Hi.


Ovaltineo said:


> What motor controller are you using? There are different modes of PWM so the motor routine might need some change.
> 
> You are lucky those motors are cheap in the US. They cost at least $300 here in Australia.


Motor controller is same as Miz's: Roboclaw dual 30A. Not the cheapest alternative by a mile but it is ready-made and easier than building my own. They claim you can reverse the motor at full current without issues - which might just mean their FETs are rated for high enough voltage/current. They also have regen on those which is nice.

Yes, if you search eBay they have gearmotors starting at about $25USD, which is what I paid for the German-made AMT ones. I'm sure the killer will be shipping those to AU as they are quite heavy. 

Don't know what you have now but if I were to start over again, I'd go with a motor and belt drive. Something like 1:10 ratio should have plenty of torque and also be quick. You can also build around them a lot easier than these behemoth from wheelchairs.

I keep going back and forth on which motor to use. On the one hand, the AMTs are the quickest at close to 190 RPM on the final shaft. On the other, the other in-line motors I have draw easily 1 full amp less at no load than the AMT, and are quieter, too.

JR


----------



## Ovaltineo (Jul 18, 2013)

The Roboclaw is a good controller, pity it doesn't have true PWM input. I suggest that you check which control input supports fail-safe (stops) when it doesn't receive a signal/command within a short period (e.g. 1 second). I'm guessing it is the RC mode. There doesn't appear to be an isolated logic power supply with this controller so there is a possibility a bad spike can cause your Arduino to hang.


----------



## Ovaltineo (Jul 18, 2013)

I'm getting two of these $18 43A BTS7960 controllers. They are nowhere near as smart as the Roboclaw but they are the right price for me.


----------



## JRoque (Mar 9, 2010)

Hello. Those look great and you can't beat that price. The max volt (27V) is a little on the low side but workable - here's hoping they let some elbow room for BEMF/peaks.

Ok this thread could get messy quickly with all the builds but here's a brief update on mine. 

First, I decided on the in-line motors. I'm now building this:










The dims are pretty much as before (26" W x 16" D X 3.8" H, 3.6" clearance - 660x406x96, 91mm). I can probably cut the width a little since the motors live under the platform/floor.

The trick now will be to fabricate some plates to fix the motors to the frame. It wouldn't be a problem if I did it exactly as my drawing above, but I found out that if I tilt the motor forward a bit then I don't have to cut the lower beam to fit it. See pic where the motor clashes with the frame. So... improvisation time.

Speaking of fabricating, I'm on a short breathing break after welding some parts in the garage. I'm using gas-less core MIG and that stuff is nasty.

You should know I've no shame so here's a pic of my crappy welds before I hide them with a grinder:










So if I report later on that I took a dive and broke a leg, your first question should be: which of the welds come apart?

JR


----------



## Ovaltineo (Jul 18, 2013)

JRoque said:


> Hello. Those look great and you can't beat that price. The max volt (27V) is a little on the low side but workable - here's hoping they let some elbow room for BEMF/peaks.
> 
> Ok this thread could get messy quickly with all the builds but here's a brief update on mine.
> 
> JR


Yeah, that max volt did worry me a bit, but according to the data sheet, absolute max voltage is 45v. I might have to change the caps on them coz they are rated at only 25v.

I really like those inline motors with the pancake gearbox! It is closer to the real Segway than anything I've seen. And those welds aren't too bad .


----------



## mizlplix (May 1, 2011)

I think I have designed around the voltage spike issue with the way I supply current to my "Duino".

I am running a nominal 24 VDC system voltage.

The Roboclaw tolerates up to 30 VDC, so the 27.5 VDC I get from a fully charged pack is acceptable. 

The "RuggeDuino" is only rated for 24 VDC, so I use a simple voltage regulator to limit it to 15 VDC input, so the full 27.5 VDC from a fully charged pack will not be an issue, nor will pack sag or (hopefully) any voltage spikes when in operation.

This is easy to do as the encoders interface with the controller and not the "Ruggeduino".

Time will tell.

The "Claw" has several operating modes for me to try to find out the best one. I plan to develop it less-encoders, THEN add encoders later to compare operation.

Miz


----------



## Ovaltineo (Jul 18, 2013)

The spike caused by the electromagnetic field collapsing in the coil and returning to the circuit has effect on both VDD and ground. Ground could become negative and this is where the problem is, especially in logic circuits. The ripple capacitor in the motor controller is supposed to absorb this, but not all the time. In my experience, avoiding ground loops is best. 
Since you are sharing the same supply as the motor controller (ground is already common), make sure you don't add an extra ground wire when connecting the logic pins between the arduino and motor controller.


----------



## JRoque (Mar 9, 2010)

Hi all. Ok calling on structural minded people. I need advise on whether the hub/wheel design below will work.

The model is of a Vespa tire and rim. The ID of the Vespa rim is 8" (203mm). The part I'm building is the star-looking support and the center hub that mates to the 17mm motor axle. 

Material: A36 steel
Star: 3/16" thick (.187"/4.76mm)
Hub: 2" (50mm) OD with 1.5" (38mm) shoulder to be welded to the star










My doubts are because the star is a flat plate with no ribs. I suppose I could weld some small U channels to the back if it was a concern but, what's your take?

JR


----------



## toddshotrods (Feb 10, 2009)

JRoque said:


> Hi all. Ok calling on structural minded people. I need advise on whether the hub/wheel design below will work.
> 
> The model is of a Vespa tire and rim. The ID of the Vespa rim is 8" (203mm). The part I'm building is the star-looking support and the center hub that mates to the 17mm motor axle.
> 
> ...


I doubt that you will break or bend 3/16" steel on a Segway. Even out at the smaller section width near the rim, it should take a pretty good shot to deform the steel spoke. I would imagine, in that case, you would have some personal issues that would overshadow the bent wheel... 

When it's welded, clamp the spokes to a flat surface, and by all means *don't quench it* - let it air cool.


----------



## JRoque (Mar 9, 2010)

That's great advise, Todd, thanks. I hadn't thought about it warping during welding. In fact, during machining, I might leave a few spots attached to the material to make it easier to clamp down while welding. If you look at my previous post weld picture, I can use all the help I can get when it comes to welding 

Ok, ordered the steel last night so it will be a couple of weekends before I can get started on that. Man, what is up with steel prices these days?! It used to be so cheap but now with China competing for every spare tin can this stuff can add up quickly.

JR


----------



## mizlplix (May 1, 2011)

Most trailer "White spoke" type wheels have much thinner steel in them.

As Todd said, after a shot that hard, you would have other issues to worry about.

Miz


----------



## toddshotrods (Feb 10, 2009)

JRoque said:


> ...If you look at my previous post weld picture, I can use all the help I can get when it comes to welding ...


Are you planning to weld the hubs in with that wire feeder? How many amps is it? I would definitely test on some scrap material to see what kind of penetration you're getting.

If not sure, that may be one thing you take to a welder.


----------



## JRoque (Mar 9, 2010)

Hi.



toddshotrods said:


> Are you planning to weld the hubs in with that wire feeder? How many amps is it?


Yep, I plan to try my own welding first. The MIG welder is 140A max. That's not a whole lot but should be good for 12ga steel. It's the operator that's at fault here. What I'm doing is getting on all the corners I can in hopes that one or two gets a proper wetting.

Last resort, I'll use fasteners as a belt and suspenders measure.

JR


----------



## toddshotrods (Feb 10, 2009)

JRoque said:


> ...should be good for 12ga steel...


3/16" is 7 gauge. If it's truly a 140 amp welder it should, in theory, handle that thickness. Your hub is substantially thicker though. A MAPP gas torch to get some heat in the pieces first might be a good idea. Some companies are pretty optimistic with the current ratings and abilities of their welders. That's why I suggested testing the penetration on scrap piece. In this case I might actually weld two pieces and cut (perpendicular to the weld) to see how well it really penetrated.


----------



## JRoque (Mar 9, 2010)

Hi.


toddshotrods said:


> 3/16" is 7 gauge.


Yes, sorry, I was referring to the square tubing that form the frame. But even that I see now it's 11ga, not 12. 



toddshotrods said:


> If it's truly a 140 amp welder it should, in theory, handle that thickness.


More corrections: it's 135A, per the manual, but *peak* which probably means just the first few seconds and then drops off a cliff.



toddshotrods said:


> Your hub is substantially thicker though. A MAPP gas torch to get some heat in the pieces first might be a good idea. Some companies are pretty optimistic with the current ratings and abilities of their welders.


Agreed, thanks for the MAPP tip.



toddshotrods said:


> That's why I suggested testing the penetration on scrap piece. In this case I might actually weld two pieces and cut (perpendicular to the weld) to see how well it really penetrated.


Will do and post the results. For now, this is what it does to 11ga square tubing.

I started this test and immediately ran out of wire. First time in 4 years since I bought the welder. I should've filmed me changing the spool, it was hilarious how I inadvertently put the roll down and a good 10' sprung out of it. Here it is, slag and all:









You might be able to see the drop inside the tube:










Just for fun, I slowed it to a stop:










Miz, any update on your code progress? Or your prototype testing?

JR


----------



## mizlplix (May 1, 2011)

My code guy is going through three samples of other's coding that they used on their vehicles.

He has told me that some of it was kinda clumsily and needs done different.

He also said that all three tackled the balancing from a slightly different perspective.....interesting...

But he is making progress, just slow.

Miz


----------



## JRoque (Mar 9, 2010)

Hello all,

A little bit of a progress report.

First, I ordered the 3/16" (4.7mm) steel plates online. But when I got an email saying it wouldn't be here until Monday, I drove to the local metal shop and bought it there. Problem is, they only had 1/4" (6.3mm) steel.

I decided to go with it since I had also found ready-made hubs that would not need welding after all. Life's good.

It took the better part of a day in the garage to rescue my (what I like to call) CNC machine from under layers of my wife's nicknacks. The ballscrews, rails and trucks where dirty and some rust was starting to show. It had been nearly 5 years since I fired that up. It also took me a day to remember how everything was supposed to work. Long story short, below are some pics of the effort.








































Beyond cutting the other wheel, I still have to machine the hubs, and make them a little shorter, to move the wheel closer to the frame. I'm hoping for an easier time with that.

JR


----------



## toddshotrods (Feb 10, 2009)

Nice work JR!  Looks awesome!

What is your CNC? What spindle speed and feed rate are you running to cut steel? No coolant or air?


----------



## JRoque (Mar 9, 2010)

Thanks! My CNC machine was DIY built from 8020 aluminum, reinforced 1/2" steel plates. I forget the exact dims but the bed is something like 48" x 48" with 10" under Z. I made the Y axis is open just so I can throw a wood slab on there and cut a door.

I ran the spindle at 2900 RPM, 18 IPM, 0.05" depth cuts, 0.25" flat endmills, except for drilling operations which was done with a ballnose. Unfortunately, my CAM program did not recognize the spoke cutouts as true arcs so it did short stop/go segments while cutting that. That translated to a slower effective IPM of about 10 on those sections.

I sprayed the work with Tap Magic once in a while. Due to slow feed rates, I ended up with steel mulch rather than chips. It took nearly two hours to cut through that but can't ask much more from a machine I built to cut wood and PCBs.

JR


----------



## toddshotrods (Feb 10, 2009)

JRoque said:


> Thanks! My CNC machine was DIY built from 8020 aluminum, reinforced 1/2" steel plates. I forget the exact dims but the bed is something like 48" x 48" with 10" under Z. I made the Y axis is open just so I can throw a wood slab on there and cut a door.
> 
> I ran the spindle at 2900 RPM, 18 IPM, 0.05" depth cuts, 0.25" flat endmills, except for drilling operations which was done with a ballnose. Unfortunately, my CAM program did not recognize the spoke cutouts as true arcs so it did short stop/go segments while cutting that. That translated to a slower effective IPM of about 10 on those sections.
> 
> ...


Nice work, and thanks for the info. That's about the same feed rate we use for aluminum on the ShopBot, but it has a router that will only go down to 10K. I tried to get them to upgrade to a spindle, but... There's a new, smaller, Laguna CNC, with a water-cooled spindle, that should be up and running in a week or so - looking forward to being able to do steel again.

Sorry for the thread jack guys - back to the Segways.


----------



## pm200107 (Aug 13, 2013)

HI there,

I'm new to the thread with a deep wish of making my own clone.

Thanks for sharing your ongoing progress. 

I'm in France, and I cant find the AMT motors. any ebay link to it?

P


----------



## JRoque (Mar 9, 2010)

Hi and welcome to the forum.

The AMT motors are just one of the many posted on eBay. I ended up going for a different kind of motor after all. I'm not sure how many of these are available within France but I would give that a try first. These motors are huge and heavy so shipping them overseas will be expensive.

There are many wheelchair motors on eBay. I have had nothing but good experience with an eBay vendor of these motors. They are a local non-profit organization that usually sell their stuff cheaper than most others. In fact, right now they have the same motors I ended up using, including all bolts, nuts and keyways for $75 plus shipping.

JR


----------



## pm200107 (Aug 13, 2013)

JRoque said:


> Hi and welcome to the forum.
> 
> In fact, right now they have the same motors I ended up using, including all bolts, nuts and keyways for $75 plus shipping.
> 
> JR


First thing first, many thanks for answering! how is your project going on?

thanks for all the links you sent. One is effectively selling at $149 with shipping costs at $199!!! that makes it a bit high!

it is a pîtty that the last link is not made available by ebay to french users... i would have checked it and maybe bought!

I hope I'll find some soon so that i can start working on it!

P


----------



## JRoque (Mar 9, 2010)

Hi.

My project is moving forward but very slowly. I cut the first wheel/spokes without a problem but the second one has been the project from hell. I hadn't notice - until last night - that the darn steel plate I was trying to cut was all warped. That meant very poor work holding. So much so that I broke two brand new end mills. First one blew up while I wasn't even in my garage so I figured something must have been wrong with the tool itself. I chucked the second one in and halfway through the cut it started vibrating violently. It was chipped before I could hit the e-stop button. 

Anyway, I'll try to work on that over the weekend or just switch to the smaller width plates that just arrived in the mail and start from zero. Those are better quality material than I get from the local metal shop.

Doing a quick check on shipping a couple motors to France I see it will take $60 to $80. The ~$50 they're charging you is not that bad but it is quite a bit to pay just for shipping. That said, I paid $30 to have them shipped 300 miles within the same state.

You might also want to look into a standalone motor with a timing belt to drive your wheels. Those should be more readily available everywhere and, perhaps, at a lower cost. I would guess that a 10:1 ratio would work for most appropriately sized motors. Those will also be quieter than gearboxes and offer more flexibility in mounting them.

JR


----------



## pm200107 (Aug 13, 2013)

JRoque said:


> Hi.
> 
> Doing a quick check on shipping a couple motors to France I see it will take $60 to $80. The ~$50 they're charging you is not that bad but it is quite a bit to pay just for shipping. That said, I paid $30 to have them shipped 300 miles within the same state.
> JR


Damn, my english is not as good as I thought... I meant $149 for the motors and $199 for the shipping, which is $348 in total!

for simplicity, as a beginner, I'll stick on the wheelchair one.. after I get something working, maybe It'll be time for improvments.

P


----------



## Ovaltineo (Jul 18, 2013)

It's been quiet in this thread so, as promised, I'll post some pics of version 1 of my Segway build. In this version, motors and electronics are mounted upside down. The only tools I used are a cordless drill, hand saw, and spanners. I used a plywood board, scooter motors and tires, Arduino Mega clone, 2x MPU6050 sensors, 2x 7ah 12 volt batteries, and custom made motor controllers. I bought a couple of heavy duty angle brackets from the hardware shop to mount the wheels to the board.


----------



## Ovaltineo (Jul 18, 2013)

I can only attach one file at a time, so I will split my posts.


----------



## mizlplix (May 1, 2011)

It looks like a good design and low center of gravity. 

I am looking forward to seeing the steering added.

Mine is out for coding, no estimate at this point.

Miz


----------



## Ovaltineo (Jul 18, 2013)

mizlplix said:


> I am looking forward to seeing the steering added.


These are actually old photos of my first clone. I can't find pics of the steering. But here is a what my motor controller looks like. I used a prototype board - which turned out to be a bad move coz the traces are too small to handle large currents. Lesson learned is to use custom PCB when making your own motor controller.


----------



## Ovaltineo (Jul 18, 2013)

I took my clone to work and found that it was too wide for standard doors - it was a pain to have to get off and carry it sideways. The components (being underside) are also easily damaged when going over rough terrain, so I decided to build version 2 of the clone. It is narrower and the components are now on top of the board. I now had to build a cover so I would have something to stand on. 
The aluminum box at the base of the steering post contains the steering sensor (MPU6050) and the separate battery for the Arduino. I used an isolated power supply for the Arduino and opto-couplers for the motor controllers to eliminate the glitches I was getting at high currents.


----------



## Ovaltineo (Jul 18, 2013)

This week, I've changed my design again, version 3 now. This time, I replaced my custom motor controllers with cheap $17 BTN7960 controllers I found in eBay. This will make it much easier for others to replicate my design. I don't think I will get glitches with these so I got rid of the separate battery for the Arduino. I replaced it with a an efficient $5 adjustable DC-to-DC converter.


----------



## Ovaltineo (Jul 18, 2013)

Here's a closeup of the BTN7960. I added a TC74 temperature sensor on the heatsink for monitoring. I will shutdown and sound the buzzer when it gets too hot. If this happens too often, I will add a fan which the Arduino can turn on when it starts to get warm.


----------



## Ovaltineo (Jul 18, 2013)

Finally, here's a photo of the steering mechanism. It is not heavy-duty (no bearings) but works well. I moved the steering sensor (MPU6050) to the end of the steering bolt. So now, the only wire going up the steering column is the safety reset switch.


----------



## JRoque (Mar 9, 2010)

Hi there. Hey good progress! I hadn't been getting updated to this thread for some reason.

Regarding heatsinking, any way you can couple your driver board's current sink to the aluminum frame? That's what I plan to do and see if I can avoid a fan.

I've been stuck waiting and searching for 14M 1.25 nuts for the motor shaft. No one seems to have those. I got tired of the waiting and cut a test one in the lathe last night. I'm going to refine it a bit, cut the second one and call it a day. 

I also ordered a new set of 1" pillow block bearings that are much smaller than the refrigerator sized ones I had previously. Hopefully that will save some space and weight. 

It's been years since I've done any lathe work. Every operation on my "high quality" Chinese lathe leads to a day or two sidetrack of fixing the darn thing. Been keeping an eye on eBay and others for some old iron machines to put an end to that frustration.

So, time, weather and family permitting, the plan for the weekend is to:
- Finish welding the motor mounts (currently only tacked in place)
- Finish the wheel nuts and mount them
- Weld a base and bolt the pillow blocks
- Work on the spring/leveler mechanics for steering column
- Weld or bolt the final two top frame members

Let's see how much of that to-do I can pull through.

JR


----------



## JRoque (Mar 9, 2010)

Hello all. A couple of pics to keep the thread active. Nothing too exciting but I did finish with my to-do with the exception of the spring/centering bit (couldn't find the darn springs in my garage).

The original plan was to mount the pillow block bearings so the steering axle intersected the Y and X planes to reduce unwanted acceleration in the sensors. I bailed out at the last minute due to the added work of precisely mounting the bearings. I settled for the sensor to live a little less than 1" (25mm) above the segway's axles.

Finished welding, drilling (for now) and prepped, sanded, ground the frame:









Primed:









Painted flat black:









JR


----------



## mizlplix (May 1, 2011)

Looks good, JR.

Miz


----------



## JRoque (Mar 9, 2010)

Thanks Miz.

Here's another brief update.

I went to mount the motors onto the frame when I noticed a huge oversight on my part. I printed only the 'right' side of the motor mounting plate and figure I would cut two of the same, then flip one for the left side. Well, I did that but totally screwed up and welded the left side the other way around. Long story short, I had to drill new holes in. It went surprisingly quick - being pissed and uttering four letter words really helped.

I took a trip to the local hardware store and bought a bunch of 45 and 90 degree elbows, pipes, joints, etc. A 1" diameter (25mm) pipe is not really 1" so I had to turn (and rethread) a couple down in the lathe to make them fit through the pillow blocks. Still working on deciding what angle and height the handle should have. Any drawings/specs/hints are appreciated.

Obligatory pics.

First, showing current status. Before I mounted the bearings and pipes, the scooter already balanced itself since most of the frame is below the axles. 










Next shows the handle prototype. The downward pointing pipe is to attach the springs so they remain inside the frame. Not sure if there's enough leverage to keep the handle upright but we'll see.










To do:

- Start putting the electronics together. Already discovered I can't use encoders with any but just one of the controller's mode. Analog is not one of them.
- Use Ovaltineo's or other code as starting point and build from there.

JR


----------



## mizlplix (May 1, 2011)

If it helps, .....on a real Segway, the handle extends 40" above the standing platform. I used a 3/4" piece of tubing made to hang a ceiling fan. A Bicycle 
handlebar wedge neck and a mountain bike straight handlebars.









I had to block the platform upright so I could stand on it in the balanced position. Then I curved the tiller until My body was in a comfortable posture for travel. (The stick was 10" from my body at the top.) That allowed me leaning room.









You are right about the controller and encoders. I plan to K.I.S.S. (Keep it simple) By trying the non-encoder modes first. If the performance suits, fine, if it is lacking ....then I will go the encoder route....last.

I am still working on the code......

Miz


----------



## Ovaltineo (Jul 18, 2013)

Miz, I'm really worried about the protruding steps in front of your machine. Until I got my hardware and software right, I've been hit about 4 times in the legs . The blunt edge of the plywood hurts (it bled once), so I can't imagine being hit by that aluminum sheet.


----------



## mizlplix (May 1, 2011)

no worries...foam padding and duct tape.

Were you standing by the machine when you turned it on or were you riding when you got hit?

I was even planning on not turning it on in the house. I watch too many utube vids.

Miz


----------



## JRoque (Mar 9, 2010)

And that's why I'm naming my segway the FP-5000. FP stands for Face Plant. The number is the expected incident occurrences. 

Hey Miz, did you get your RoboClaw driver working? I'm having problems with mine and have a question into their support forum about it. 

It is acting weird. I added a pot to each of the inputs, set the mode to #3, Analog. Moving the pot on S1 input speeds up/down/rev both motors at a time. The pot on S2 doesn't do anything. 

Another surprise from the Analog mode is that it sets the motors to full reverse speed at 0V input. That's right, if your control board (ie: Arduino) doesn't come up, or quick enough, your segway will lurch to a full speed reverse kamikaze dive. I can cure that with a contactor but I thought it shortsighted of them to make it work that way.

I then switched to RC mode but setting up for 10uS pulses is tough on the little Atmel chips. Fortunately there's nothing much else to do because there aren't many cycles to spare. I'm still working on refining the pulses via my own code (not Arduino).


----------



## Ovaltineo (Jul 18, 2013)

mizlplix said:


> no worries...foam padding and duct tape.
> 
> Were you standing by the machine when you turned it on or were you riding when you got hit?
> 
> ...


Yes, foam padding is a good idea. Twice, I was actually riding it when the tilt was more than the machine can catch (going uphill) so I had to jump in front. The other times I was beside it when it decided to do the "spin of death". Once was because I wired one of the motors in reverse. The other was when one of the MOSFETS shorted after overheating - lucky I moved the power switch fom inside the enclosure to outside because my emergency reset didn't work with this scenario. I thought MOSFETs always blew open instead of shorting .

Yes, never use it inside the house unless you want to do some re-decorating .


----------



## mizlplix (May 1, 2011)

I am in the process of recovering my hardware back from the coding guy (Who is having family issues), so I can restart debugging the code from where he left off.

We are working on the small balancing robot ATM.

I have not gone into the Roboclaw too deep yet, so can not help you there.

To date: we have not gotten it to self-balance.

Miz


----------



## Ovaltineo (Jul 18, 2013)

I too built a small balancing robot to test my software. I didn't get it to balance, but it was close. It was a tall robot so needed fast response. I figured it was because my geared motor was too slow for the job. I found that it was much easier to balance on the real thing coz it balanced without power and the motors were up to the job.


----------



## mizlplix (May 1, 2011)

Ovaltineo said:


> I too built a small balancing robot to test my software. I didn't get it to balance, but it was close. It was a tall robot so needed fast response. I figured it was because my geared motor was too slow for the job. I found that it was much easier to balance on the real thing coz it balanced without power and the motors were up to the job.


You have a valid point.

I imagine I would perform the balancing part of the debugging with no steering input connected. That way it would be relatively safe to stand beside the Segway. After it balances well would be the time to connect the steering and debug it second.

Miz


----------



## Ovaltineo (Jul 18, 2013)

Yes, I also added steering when I got the balancing right.

I've been busy finishing up the steering post of my macihine. I figured I needed something adjustable so that kids and tall adults can use it. It was tedious work to make sure the holes aligned, especially since I'm drilling free-hand without a drill press.


----------



## battagae (Aug 13, 2013)

Ovaltineo, I'm wondering exactly funduino or arduino mega you used there seems to be quite a bit or are they all they same? Also you don't mention anything about using a potentiometer in your design. Lastly how much of a difference would 6 gyro-accelerometer's make over 3?


----------



## Ovaltineo (Jul 18, 2013)

Funduino is a mega clone. I didn't use a potentiometer for the steering because I don't think they will last too long. I used another accelerometer for the steering. To measure the board tilt, you only need 1 gyro on the y axis and 1 accelerometer on the x axis. It just happens that the MPU6050 had 1 for each axis. If you mount the MPU6050 on the steering shaft, you can also use the y axis accelerometer to measure the steering angle.


----------



## Ovaltineo (Jul 18, 2013)

I developed "bearing envy"  from Miz and JR's design so I bought a couple from ebay. I didn't think 8mm bearings wold be so small - they were posted in a small envelope! Anyway, they went in easily - just needed to drill a few more holes.


----------



## Ovaltineo (Jul 18, 2013)

Here's what it looks like with the new extendable handle.


----------



## JRoque (Mar 9, 2010)

Hey that looks great. How's the tension with those springs you're using? I think I may have overdone yet another thing with the springs I chose - they are tight. I like your idea of a lighter weight handle instead of a steel tube like I was planning to have. I'm guessing the handle will be there more to keep balance than to support the rider's weight pulling and whatnot.

The 8mm bearings are pretty small but it might work fine if the axle is good steel. Do you get much flexing in there?

I sent the RoboClaw DC controller back to the manufacturer for a checkup. Something's definitely not right with it. I'm hoping they turn that around quickly so I can get back to experimenting and coding.

BTW, I spoke with the support guys at Orion and they said version 4 of the RoboClaw does support encoders in analog mode - new feature they added. If you bought a V3 recently, they should be able to flash it with the latest code if you send them the unit.

JR


----------



## Ovaltineo (Jul 18, 2013)

Because the shaft is small in diameter and the post is box aluminum, there is some flexing where they meet. That's where your heavy duty design is superior. Also, the post is just a straight box, so it ends up too close to the rider. 

I have an opposite problem with the springs - they are too soft so self-centering isn't very good.

But for something that was built with a handsaw, hand drill, and a soldeing iron -all for under $300, I can't complain too much.


----------



## mizlplix (May 1, 2011)

JR: thanks for the heads up on the controller, I think I will send it in to be reflashed.

Oval: Looking good. I should be getting my stuff back this weekend and can start straightening out some code. I will keep everyone posted on my progress.

I am a tad rusty...LOL

Miz


----------



## Ovaltineo (Jul 18, 2013)

Ovaltineo said:


> Miz,
> I think I may have a simple solution to the gyro/accelerometer steering problem.
> 
> board_y_angle=getBoardYAngle();
> ...


I tested this code yesterday and it worked -- sort of. On a slight bank, it works well because I can keep the handle perpendicular to the board and the machine doesn't turn. But on a medium to steep bank, trying to keep the handle perpendicular to the board while I'm trying to keep my body upright is awkward - I will naturally bring the handle upright to keep my balance. Because the handle will not be perpendicular to the board, this will make an unintended turn. Also, when I go offroad (e.g. grass) the quick changes in the angle of the ground makes the machine turn slightly left and right with every bump. So I went back to the single accelerometer steering.

Lesson learned - using dual accelerometer (or potentiometer) for steering is not good with my soft springs. I think it should work with a stiff springs because it is easier to keep the handle perpendicular to the board if you don't want to make a turn.

Anyway, here's a video of my son riding the machine (very slowly) for the very first time.


----------



## mizlplix (May 1, 2011)

Oval: I just got all of my stuff back and will start working on it this week...

Your steering solution looks good.

My centering springs are VERY stiff and I have a 41" long tiller, so it should work spiffy.

Miz


----------



## Ovaltineo (Jul 18, 2013)

I finally managed to test the "clean" code I posted here a few weeks ago. Well, I found a few bugs and fixed them. I also added support for a potentiometer in the steering (instead of an accelerometer). So here it is.


----------



## phaedrus (Aug 24, 2013)

I thought I'd drop in and say hello....

Around 5 or 6 years ago I started making a segway clone out of an old mobility scooter, much as you are doing, or have done, here. At the time I believe it was a fairly unique approach.

It's interesting to see that now this is not an uncommon method, and that quite a number of people have done this. For me, as Mr Lennon said, 'life is what happens while you're making plans', or something like that, and so I never did finish the project.

However I am now back on to it and have been interested to follow your progress - I looked at your code OT and tried the PID loop with my codebase to see how it would go. The answer is not well, but then it was just a fairly brief try to see what'd happen rather than a concerted or intelligent effort!

FYI I am also using an MPU6050 for the IMU, but I used Jeff Rowbergs library to get the data, for no particular reason other than that it seemed to be the most recent at the time.

In time, and assuming no more local natural disasters (long story), I'm interested in messing with a direct drive BLDC motor variant - it would be good to further the research/knowledgebase rather than merely follow on from others. 

Anyway if it's ok I will keep an eye on this thread and may drop in from time to time.. keep up the good and interesting work!

Cheers, P.


----------



## Ovaltineo (Jul 18, 2013)

phaedrus said:


> However I am now back on to it and have been interested to follow your progress - I looked at your code OT and tried the PID loop with my codebase to see how it would go. The answer is not well, but then it was just a fairly brief try to see what'd happen rather than a concerted or intelligent effort!
> 
> Cheers, P.


Phaedrus, please post your code so I can help you debug it. The PID loop is a well known algorithm and the last place I would look for a problem (except for the PID constants that need a lot of tweaking). I would start by not plugging the motors - like in my code, print the accelerometer, gyro, computed angle, and motor values to a serial port and view with a serial monitor. If you are not using an Arduino, then you need a way to look at these values in real time. 
A word of warning to everyone - it is very dangerous to plug in the motors unless these values look reasonable.


----------



## phaedrus (Aug 24, 2013)

Thanks OT, don't worry, no-one was harmed in this test  I did exactly as you describe re the serial printout, and I had a small model motor on a PWM board just to see what was happening empirically.

Yes the PID routine is fairly well known, and nothing in your code looked at all odd from memory. I expect it was just that the values I was inputting weren't right - although the angles I was printing out looked ok. Unfortunately I'm not anywhere near that machine presently, and won't be for a few days, so I can't check for sure or do any more on it right now, sorry. Once I do get there I'll have a closer look and see what's going on and post up where I'm at with that code.

As an aside it's interesting to see there's a good number of balancing scooters around that use handmade filters of various means, or just PD loops, to control the motors. IIRC the Zzaag, and even Trevor Blackwell's didn't have a PID routine per se? So many ways to skin the cat, so to speak!

Incidentally I am using an Arduino, I'm impressed with what they can do - although I just wish I could code it in Python (or even Pascal), C annoys me 

Cheers, P.


----------



## mizlplix (May 1, 2011)

Welcome to the thread and forum Phaedrus.

I am going to do one try at my balancing model robot, then if not successful, transplant all of the stuff back into the Segway and just do it there.

I made a test stand to place the whole Segway onto and it keeps the wheels off the floor, so I can leave the motors plugged in and lets me tilt the platform 
and watch the wheel rotation.

I am starting out with this code:

//------------------------------------------------------------

int xPin = 2; // select the input pin for the potentiometer
int gyroPin = 1;
int steerPin = 3;
int ledPin = 13; // select the pin for the LED
int pwmPinL = 9;
int pwmPinR = 10;
int enPin = 7;

float angle = 0;
float angle_old = 0;
float angle_dydx = 0;
float angle_integral = 0;
float balancetorque = 0;
float rest_angle = 0;
float currentspeed = 0;
int steeringZero = 0;
int steering = 0;
int steeringTemp = 0;

float p = 8; //2
float i = 0; //0.005
float d = 1300; //1000

float gyro_integration = 0;
float xZero = 0;
int gZero = 445; //this is always fixed, hence why no initialisation routine
unsigned long time, oldtime;
int pwmL;
int pwmR;
boolean over_angle = 0;



void setup() {
unsigned int i = 0;
unsigned long j = 0; //maximum possible value of j in routine is 102300 (100*1023)

pinMode(ledPin, OUTPUT); // declare the ledPin as an OUTPUT
Serial.begin(115200);
analogReference(EXTERNAL);
//----------------------------------------------------
TCCR1B = TCCR1B & 0b11111000 | 0x01;
analogWrite(pwmPinL,127);
analogWrite(pwmPinR,127);
digitalWrite(enPin,HIGH);
pinMode(enPin,OUTPUT);
digitalWrite(enPin,LOW);
//-----------------------------------------------------
delay(100);
for (i = 0; i < j =" j" steeringzero =" analogRead(steerPin);" xzero =" j/100;" oldtime =" micros();" time =" micros();">= (oldtime+5000)){
oldtime = time;
calculateAngle();

steering = (analogRead(steerPin) - steeringZero)/(15+(abs(angle)*8));

//-----OVER ANGLE PROTECTION-----
if (angle > 20 || angle < -20) { digitalWrite(enPin,HIGH); over_angle = 1; delay(500); } //-----END----- if (over_angle) { //if over_angle happened, give it a chance to reset when segway is level if (angle <> -1) {
digitalWrite(enPin, LOW);
over_angle = 0;
}
}
else {

//-----calculate rest angle-----
if (currentspeed > 10)
{
rest_angle = 0;
//-----END----- 
angle_integral += angle;
balancetorque = ((angle+rest_angle)*p) + (angle_integral*i) + (angle_dydx*d); 
angle_dydx = (angle - angle_old)/200; //now in degrees per second
angle_old = angle;
currentspeed += (balancetorque/200);

pwmL = (127 + balancetorque + steering);

//-----COERCE-----
if (pwmL < pwml =" 0;"> 255)
pwmL = 255;
//-----END-----

pwmR = (127 - balancetorque + steering);

//-----COERCE-----
if (pwmR < pwmr =" 0;"> 255)
pwmR = 255;
//-----END-----

analogWrite(pwmPinL, pwmL);
analogWrite(pwmPinR, pwmR);
}
}
}

void calculateAngle() {
//Analogref could be as small as 2.2V to improve step accuracy by ~30%
//uses small angle approximation that sin x = x (in rads). maybe use arcsin x for more accuracy?
//analogref is off the gyro power supply voltage, and routine is calibrated for 3.3V. maybe run acc/gyro/ref off 1 3.3V regulator, an
//accurately measure that.
//routine runs at 200hz because gyro maximum response rate = 200hz
float acc_angle = 0;
float gyro_angle = 0;

acc_angle = (((analogRead(xPin)-xZero)/310.3030)*(-57.2958);
gyro_angle = ((analogRead(gyroPin) - gZero)*4.8099)/200;
gyro_integration = gyro_integration + gyro_angle; //integration of gyro and gyro angle calculation 
angle = (gyro_integration * 0.99) + (acc_angle * 0.01); //complementary filter
gyro_integration = angle; //drift correction of gyro integration

} 

I am using a Roboclaw
a Ruggeduino 
a P80 IMU- (with 3 axis Gyro, 3 axis Acc-Baro- GPS)


I am only going to use the gyro "X" and "Z" outputs.

I am not good enough to just visually go through all of the code and guess what it is going to do, I need to plug it in....

It has been many years since I have done any meaningful amount of coding, so it will be extremely slow unless I get some help along the way from a kindly few souls... : )

Miz


----------



## JRoque (Mar 9, 2010)

Hello all.

Thanks for the code, Ovaltineo! I'm going to drop that in as soon as my dc controller is back.

Welcome to the forum P.



phaedrus said:


> Incidentally I am using an Arduino, I'm impressed with what they can do - although I just wish I could code it in Python (or even Pascal), C annoys me
> Cheers, P.


You and me both. Luckily Arduino is an Atmel chip on a proto board so I can use my favorite compilers for basic and assembler. I found a way to send my code using the Arduino's boot-loader which lets me flash the code via the existing USB port.



mizlplix said:


> I am not good enough to just visually go through all of the code and guess what it is going to do, I need to plug it in....
> 
> Miz


Yep, that's me, too. So much so that I have not done a thing since I sent my RoboClaw board back to Orion for repairs nearly 2 weeks ago. Don't bother overnighting stuff to Orion, they are busy and take their time.

Looking at the code, it appears you're using PWM outputs to drive the controller. Did you filter those outputs yet? The controller needs a smooth analog voltage input. 

BTW, did you notice how it sprints to max terror - backwards - a full speed when the input is not connected to anything? That's just scary, if not idiotic. At no input, it should not move at all. Until I find a suitable contactor, I think there's a pin on the board that routes 5V to the ucontroller. I might use a small reed relay there as a way to inhibit the controller until the Arduino is up and running and under control.

JR


----------



## mizlplix (May 1, 2011)

I think that is why some guys are using foot operated momentary buttons.

You turn on your main power switch. 

The Arduino boots up. 

When you mount, (the first foot is placed) the Controller turns on.

OR alternatively, you can have a delay relay to do it:

Turn on the main pack switch, 

The arduino boots.

The time delay relay powers up the controller.


No, I have not placed any filters in the PWM output to the controller.

I have just borrowed this code as the closest I could find that matched my equipment. I was under the asumption that the controller was OK with a PWM input. At least I read that.

Something like..."The analog outputs from the arduino are not fast enough, so use the PWM to signal the controller." No mention of a filter, although that is a basic idea I had not considered. 

What filters do you suggest? A Kalman type filter perhaps?

Miz


----------



## JRoque (Mar 9, 2010)

mizlplix said:


> I think that is why some guys are using foot operated momentary buttons.
> 
> You turn on your main power switch.
> 
> ...


Right, I also have the foot switches pending to be added later on. I'm thinking both switches must be off (ie: rider off the scooter) before the segway does a fast ram down stop. I wouldn't want to trigger that with just one switch off.

If you keep VDD cut out from the board's logic, it won't run. So a small reed relay, normally off, can be installed and controlled by the Arduino when it's good and ready. 




mizlplix said:


> No, I have not placed any filters in the PWM output to the controller.
> 
> I have just borrowed this code as the closest I could find that matched my equipment. I was under the asumption that the controller was OK with a PWM input. At least I read that.
> 
> ...


Before I realized my board was bad, I had added a voltage divider to float the inputs at 1V, which meant the motor would not run without input. I had also added a 1uF tantalum cap to smooth out the PWM signal. Nothing fancy but it should work. Perhaps 1uF will add too much delay as I'm getting a sense of needing max speed motor tuning for balancing.

I read somewhere in the manual that PWM signals should be rectified somewhat when using analog mode. I doubt their analog mode will be able to track a PWM input signal in a way that affects the motor output. Plus the added capacitance between the Arduino and the controller connections could be just enough to keep the input stable.

JR


----------



## Ovaltineo (Jul 18, 2013)

Given the limitations of analog input on the Roboclaw, I would suggest going to packet serial instead. This means that you can use S3 as en enable pin. In this mode, this pin is pulled high on the Roboclaw (normally disabled), so you just need to do a digitalWrite(pin, LOW) in the setup routine. This means you don't need a separate disable switch.

Also, you must use packet serial, not simple serial. Like analog/RC mode, simple serial has a fatal flaw where a host reset can be interpreted as a 255 command - full forward! Also, packet serial has a checksum, so a glitch on the serial data is not likely to cause a problem.


----------



## mizlplix (May 1, 2011)

What he said.


----------



## JRoque (Mar 9, 2010)

Hi. Yep it's limited alright. I got the board back last night. Plugged it in, used a couple of pots and the darn thing is exactly as it was when I shipped it to them. I wasted 2 entire weeks waiting for the stupid thing to be "fixed" and it wasn't.

I wanted to use some sort of digital mode from the start but I hear that the latency of a serial protocol is too much to make it usable in this application. Serial mode does have some niceties like providing bus voltage and motor current. I may have no choice but to use that since analog mode simply does not work. Even if it did, as you point out, a 0V or 2V input makes it go full throttle in either fwd or rev... nice.

JR


----------



## phaedrus (Aug 24, 2013)

JR: I've no experience with the Roboclaw but just to put something else in the mix and FYI I am using a motor controller with discrete IRF4205's, not completely dissimilar to the original Zzaag/Elektor design. If I'd looked harder and spotted the BTS7960 modules I might have gone for them - good current capacity if the specs are to be believed...

That aside I suspect OT will have a much better grasp of these things than I but I would have thought that you'd not experience too much of an issue with the speed of the serial mode? Although I imagine the packet serial OT talks about will add some data overhead it's probably still well within the capacity of the overall system to adequately control the motor movement in time. 

OT: I've not had a chance to get to my other machine yet but did have a play with your revised code and a spare MPU6050 I've got. I was interested to see that the 'centre' or zero angle position seemed very sensitive (printing the data out) and that unless one moved it constantly either side of zero the motor control would max out in one direction or another. This seems at odds with what I've seen previously but is that how you have it working? Other than comment out the PWM frequency setting (which the compiler objected to), and setting the P, I & D values per your recommendations I made no changes so it should be fairly much as you have it.

That said it certainly looked a lot more proportionally correct than what I'd come up with last - as I recall that ran away as well but it clearly wasn't quick enough to deal with any major change in tilt!

Amyway I started making a new chassis frame for my unit today, this has now become a bit of a project for my son also - at least that's what I've determined! We cut up parts of an old conveyor system I had here to get some 40x40x3 angle, and then welded them into the framework, so he can now start to see the concept turning into some sort of reality. The mobility scooter motors I'm using aren't ideal given their right angle gearbox etc so they tend to intrude a bit into the platform space (given the way I designed it) but they'll do as a 'proof of concept' until I sort something better - as far as the boy's education side of things is concerned I'm sure it's all good!

Once I've got the motors mounted in the next week or so I'll put up a photo of the framework if anyone's interested.

Cheers, P.


----------



## Ovaltineo (Jul 18, 2013)

phaedrus said:


> If I'd looked harder and spotted the BTS7960 modules I might have gone for them - good current capacity if the specs are to be believed...


Yes, the BTS7960/BTN7960 has great specs - good capacitty, true PWM, enable pins, built-in temperature and current limiting - all for $17. A true bargain that's why I'm now using them!



phaedrus said:


> That aside I suspect OT will have a much better grasp of these things than I but I would have thought that you'd not experience too much of an issue with the speed of the serial mode? Although I imagine the packet serial OT talks about will add some data overhead it's probably still well within the capacity of the overall system to adequately control the motor movement in time.


At 115Kbps, I imagine the propagation and processing delay would be much less than the 10ms refresh time of the complementary filter/PID loop of the Segway. I certainly did not notice the delay when I used my custom made motor controller with serial connection. I did notice the glitches though. I have now figured out why I was getting glitches (it was a hidden ground loop), but I am now using the much better BTN7960 with PWM.



phaedrus said:


> OT: I've not had a chance to get to my other machine yet but did have a play with your revised code and a spare MPU6050 I've got. I was interested to see that the 'centre' or zero angle position seemed very sensitive (printing the data out) and that unless one moved it constantly either side of zero the motor control would max out in one direction or another. This seems at odds with what I've seen previously but is that how you have it working? Other than comment out the PWM frequency setting (which the compiler objected to), and setting the P, I & D values per your recommendations I made no changes so it should be fairly much as you have it.
> 
> Cheers, P.


What you are noticing about the sensitive angle and how it would quickly max out is normal. That's because you are testing without any wheels -- the PID will quickly increase the motor output if there are no feedback that make corrections to the angle. At this point, I would set the MAX_MOTOR to a low number (say 30) and put on the motors and wheels. If everything is working, then it would balance. If something is wrong, then the low MAX_MOTOR will at least keep your machine from going berserk.

I think you are very close to getting your machine to balance.


----------



## mizlplix (May 1, 2011)

I am about to throw this back in the storage room. I am spending way too much time trying to get a code to work. Having tried several codes I got off of the internet, I fail to get any to at least go through the "verify" stage in the Arduino software client.


They ALL are flawed. How did they work then? 

Example: The latest version: It fails at the first mention of the term "BYTE". It says it is not supported and to change it to "Serial.write" instead.

When I do, It fails again: "No matching function to "Hardware serial write"

The line is about 57 lines from the bottom. Place your cursor on the bottom bracket symbol and cursor up 57 times and you should be there.

BTW: this is the best code I have found for the Arduino. The rest have mega flaws. Too much for me to debug.

I am lost at this point. Miz
________________________________________________________________

// DIY Seg-bot 
// 2011 
// Arduino Duemilanove (tested)
// Sparkfun Razor 6 DOF IMU - only using X axis from accelerometer and gyroscope 
// Steering potentiometer used to steer bot
// Gain potentiometer used to set max speed (sensitivity) 
// Engage switch (button) used to enable motors
// 



// use SoftwareSerial library to communicate with the Sabertooth motor-controller
#include <SoftwareSerial.h> 
// define pins used for SoftwareSerial communication
#define rxPin 2
#define txPin 3
// set up a new SoftwareSerial port, named "mySerial" or whatever you want to call it.
SoftwareSerial mySerial = SoftwareSerial(rxPin, txPin);


// Name Analog input pins
int gyro_pin = 1;
int accel_pin = 5;
int steeringPot = 3;
int gainPot = 2;

// Name Digital I/O pins
int engage_switch = 4;
int ledPin = 13;

// value to hold the final angle 
float angle = 0.00;
// the following 2 values should add together to equal 1.0
float gyro_weight = 0.96;
float accel_weight = 0.04;

// accelerometer values
int accel_reading;
int accel_raw;
int accel_offset = 511;
float accel_angle;
float accel_scale = 0.01;

// gyroscope values
int gyro_offset = 391;
int gyro_raw;
int gyro_reading;
float gyro_rate;
float gyro_scale = 0.04; // 0.01 by default
float gyro_angle;
int loop_time = 60; // this is the loop time in milliseconds
float loop_cycle = loop_time / 100; // this is the loop time / 100 to get the time in seconds

// engage button variables
int engage = false;
int engage_state = 1;

// timer variables
int last_update;
int cycle_time;
long last_cycle = 0;

// motor speed variables
int motor_out = 0;
int motor_1_out = 0;
int motor_2_out = 0;
int m1_speed = 0;
int m2_speed = 0;
int output;

// potentiometer variables
int steer_val;
int steer_range = 7;
int steer_reading;
int gain_reading;
int gain_val;

// end of Variables


void setup(){

// Start the Serial monitor at 9600bps
Serial.begin(9600);
// define pinModes for tx and rx:
pinMode(rxPin, INPUT);
pinMode(txPin, OUTPUT);
// set the data rate for the SoftwareSerial port
mySerial.begin(9600);

// set the engage_switch pin as an Input
pinMode(engage_switch, INPUT);

// enable the Arduino internal pull-up resistor on the engage_switch pin.
digitalWrite(engage_switch, HIGH);
// Tell Arduino to use the Aref pin for the Analog voltage, don't forget to connect 3.3v to Aref!
analogReference(EXTERNAL);

}

void loop(){
// Start the loop by getting a reading from the Accelerometer and coverting it to an angle
sample_accel();
// now read the gyroscope to estimate the angle change
sample_gyro();
// combine the accel and gyro readings to come up with a "filtered" angle reading
calculate_angle();
// read the values of each potentiomoeter
read_pots();
// make sure bot is level before activating the motors
auto_level();
// update the motors with the new values
update_motor_speed();
// check the loop cycle time and add a delay as necessary
time_stamp();
// Debug with the Serial monitor
serial_print_stuff();

}




void sample_accel(){
// Read and convert accelerometer value

accel_reading = analogRead(accel_pin);
accel_raw = accel_reading - accel_offset;
accel_raw = constrain(accel_raw, -90, 90);
accel_angle = (float)(accel_raw * accel_scale);
}

void sample_gyro(){
// Read and convert gyro value

gyro_reading = analogRead(gyro_pin);
gyro_raw = gyro_reading - gyro_offset;
gyro_raw = constrain(gyro_raw, -391, 391);
// if when you tilt your Arduino/IMU, the gyro and accel readings go in opposite directions... change the loop_cycle variable to be negative or positive (opposite its current state)
gyro_rate = (float)(gyro_raw * gyro_scale) * -loop_cycle;
gyro_angle = angle + gyro_rate;
}

void calculate_angle(){
angle = (float)(gyro_weight * gyro_angle) + (accel_weight * accel_angle);
}

void read_pots(){
// Read and convert potentiometer values
// Steering potentiometer
steer_reading = analogRead(steeringPot); // We want to coerce this into a range between -1 and 1, and set that to steer_val
steer_val = map(steer_reading, 0, 1023, steer_range, -steer_range);
if (angle == 0.00){
gain_reading = 0;
}
// Gain potentiometer
gain_reading = analogRead(gainPot);
gain_val = map(gain_reading, 0, 1023, 32, 64);
}

void auto_level(){
// enable auto-level turn On
//engage_state = digitalRead(engage_switch);

if (digitalRead(engage_switch) == 1){
delay(10);
if (digitalRead(engage_switch) == 1){
engage = false;
}
}
else {
if (engage == false){
if (angle < 0.02 && angle > -0.02)
engage = true;
else {
engage = false;
}
}
else {
engage = true;
}
}

}

void update_motor_speed(){
// Update the motors

if (engage == true){
if (angle < -0.4 || angle > 0.4){
motor_out = 0;
}
else {
output = (angle * -1000); // convert float angle back to integer format
motor_out = map(output, -250, 250, -gain_val, gain_val); // map the angle
}

// assign steering bias
 motor_1_out = motor_out + (steer_val);
motor_2_out = motor_out - (steer_val);

// test for and correct invalid values
if(motor_1_out > 64){
motor_1_out = 64;
}
if(motor_1_out < -64){
motor_1_out = -64;
}
if(motor_2_out > 64){
motor_2_out = 64;
}
if(motor_2_out < -64){
motor_2_out = -64;
}

// assign final motor output values
m1_speed = 64 + motor_1_out;
m2_speed = 192 + motor_2_out;
}

else{
m1_speed = 0;
m2_speed = 0;
}

// write the final output values to the Sabertooth via SoftwareSerial
mySerial.print(m1_speed, BYTE);
mySerial.print(m2_speed, BYTE);
}

void time_stamp(){
// check to make sure it has been exactly 50 milliseconds since the last recorded time-stamp 
while((millis() - last_cycle) < loop_time){
delay(1);
}
// once the loop cycle reaches 50 mS, reset timer value and proceed
cycle_time = millis() - last_cycle;
last_cycle = millis();

}


void serial_print_stuff(){
// Debug with the Serial monitor

Serial.print("Accel: ");
Serial.print(accel_angle); // print the accelerometer angle
Serial.print(" ");

Serial.print("Gyro: ");
Serial.print(gyro_angle); // print the gyro angle
Serial.print(" ");

Serial.print("Filtered: ");
Serial.print(angle); // print the filtered angle
Serial.print(" ");

Serial.print(" time: ");
Serial.print(cycle_time); // print the loop cycle time
Serial.println(" ");

/*

Serial.print("o/m: ");
Serial.print(output);
Serial.print("/");
Serial.print(motor_out);
Serial.println(" "); 

Serial.print("steer_val: ");
Serial.print(steer_val);
Serial.print(" "); 

Serial.print("steer_reading: ");
Serial.print(steer_reading);
Serial.print(" "); 

Serial.print("m1/m2: ");
Serial.print(m1_speed);
Serial.print("/");
Serial.println(m2_speed);
*/
}


----------



## JRoque (Mar 9, 2010)

Hey Miz,

Disclaimer: I know nothing about Arduino.

Searching a bit I see that byte mode in the serial command has been deprecated. You have a newer version of the Arduino compiler than was used to build that code. 

You might be able to send it like this: Serial.print(MyVar). Take the "byte" part out and see if it compiles.

I agree with you that most code from the interwebs do not work. I'm going to give it a try first but I'll likely end up diving in and doing all from scratch. Hang in there, the curve is steep at first but once you get it to balance it will get easier.

JR


----------



## phaedrus (Aug 24, 2013)

MZ: I'm sorry but I have neither analogue gyro/accelerometers, nor a Robo controller to try and replicate your setup empirically but to follow on from JR's comments if you replace the lines:

mySerial.print(m1_speed, BYTE);
mySerial.print(m2_speed, BYTE);

with:

mySerial.write(m1_speed);
mySerial.write(m2_speed);

it should compile (at least it does for me). What happens from there is another thing!

I see that this code writes to the software serial ports at 9600, which is somewhat slower than the 115k one might otherwise expect. Perhaps this is a limitation of the software serial vs hardware serial in the Arduino but it will be interesting to see how it works - given there won't be much data it writes to the controller (I assume) it should be ok.

From somewhat hazy memory with my code it took around 4msec to complete all the tasks in the loop using the I2C data from the gyro/acc, calculating the necessary angles etc and outputting that via PWM. My loop timing was 10msec so it left 6msec 'spare' so to speak - I think your code uses 50msec timing so it hopefully it'll have plenty spare.

Like JR I must add a disclaimer that, in my case, I'm really no programmer so please take at least half of what I say as complete rubbish! However I also completely agree with him that this is simply a process to work through, frustrating though it may be, and it will be very satisfying once you get something to happen - even if it doesn't quite work perfectly at first. Unless you *completely* replicate what someone else has done it's likely there will be some messing around that you have to do; generally in the process you'll learn a lot, and probably contribute to the community as a result when you've finished hacking things around... so keep at it and let us know how it goes.

OT: Thanks for the comments, I suspected as much with the empirical test, albeit that I tried to compensate a little with my movement of the MPU6050. Given I'm still building the hardware it may take a little while to actually test it but it's good to know that what I was seeing appears normal. It does suggest that my code was a bit sluggish to get its control speeds up.

I will see how I go with my current controller but I can see myself getting some of those BTS modules soon...


----------



## esoneson (Sep 1, 2008)

From the Arduino info ( http://arduino.cc/en/Serial/Print )



An optional second parameter specifies the base (format) to use; permitted values are BIN (binary, or base 2), OCT (octal, or base 8), DEC (decimal, or base 10), HEX (hexadecimal, or base 16). For floating point numbers, this parameter specifies the number of decimal places to use. For example: 


Serial.print(78, BIN) gives "1001110"
Serial.print(78, OCT) gives "116"
Serial.print(78, DEC) gives "78"
Serial.print(78, HEX) gives "4E"
Serial.println(1.23456, 0) gives "1"
Serial.println(1.23456, 2) gives "1.23"
Serial.println(1.23456, 4) gives "1.2346"


Didn't look to see what is trying to be accomplished. But these are your choices.

Eric


----------



## esoneson (Sep 1, 2008)

Miz,

From another source:

Find Serial.print(0, BYTE), Replace All with Serial.write( byte(0) ).

A simple replace like that suggested by phaedrus should get you past this syntax error.

Eric


----------



## mizlplix (May 1, 2011)

Thanks guys, Im back on it.

Miz


----------



## Ovaltineo (Jul 18, 2013)

Miz, the latest code you posted has static gyro and accelerometer values - there is no provision to calibrate the sensor. It is also using Simple serial which should be changed. Some of the values are unexplained and some of the comments are wrong, eg "this is the loop time /100 to get the time in seconds" - it should be /1000. In short, it may work but without the original coder to help you, it may be a bit frustrating.

I can add support for the Roboclaw in my code. But I hesitate to add support for another accelerometer and gyro, because I cannot test it and the far superior MPU6050 (sounds like I work for the manufacturer ) is less than $4.


----------



## mizlplix (May 1, 2011)

I would be tickled pink to use ANY code that works. I will gladly change to whatever hardware required.

I feel it is a bigger job straightening out some old code that used different hardware and make everything function correctly.

Do you recommend a supplier for the MPU6050 gyro?

I have an Uno, Roboclaw, Will buy a MPU6050 , And plan to just mount it to the base of the stick.

Now all I need is a code.......


[email protected]


----------



## phaedrus (Aug 24, 2013)

MZ: I would agree with OT that the MPU6050 works well and is inexpensive. I've purchased mine from a couple of different suppliers on Aliexpress and that worked well (although I recently ordered five of the MPU's so I had a couple to spare but they only shipped one ) . They use I2C to communicate, your Uno should be fine if you wanted to go that way (I'm using one), and perhaps you could consider getting a couple of the BTS controller modules as well since you'd need to wait for the MPU to arrive.

Personally I tend to order additional items of something when I'm getting things, so that I have extra if I blow something up, and also the next time I want one they're to hand... so if you've not got a spare Arduino you might want to think about that too - from aliexpress or ebay you'd get all you need for making a segway like OT's (electronically that is!), including spares, for circa $100 USD. If you've not got a 24v to ~9v or 5v converter you might want to look at one of those as well (also about $4 - better than messing around with a 7805 or whatever, they'll handle a 19v drop happily and stay cool).

From there you could use OT's code with whatever mods you'd need/want to make.

That said, and to be fair to the hardware you've presently got, there are a number of Segway clones around that use analog sensors and Arduino's quite successfully (I assume with the Robo as well, just that I've no experience with that) so you *could* use it - it's just that, so far, none of us here can replicate what you've got to help you through anything much. Mind you I'm the new kid on the block and shouldn't be casting such aspersions - perhaps someone here does have your kit and can help!

In the interim it could be interesting, and somewhat educational to at least set up your Uno with your present analog gyro etc and see what sort of output you can get (printing to your computer) with that code you've got. While you wouldn't necessarily use it in your machine it would give you an idea of how things work and I reckon that a bit of tinkering can teach a lot... I've learnt quite a bit just messing with the Uno and MPU screwed to a board that I can wave around in the air - I used the teapot pde initially to give me an idea of things visually, which was a bit of a boost to the ego to see something for all these wires and things 

If you were determined to use the analog sensors then I do have various bits of successful code that use them that I'd be happy to pass on to you, but as I said previously you'd need to replicate the setups *exactly* for any guarantee that they'd work. In all probability you'd have to do quite a bit of work with the code to fit your hardware, and if you're not so familiar with coding then you'd probably be no further ahead than you are now.

Cheers, P.


----------



## Ovaltineo (Jul 18, 2013)

mizlplix said:


> Do you recommend a supplier for the MPU6050 gyro?
> 
> I have an Uno, Roboclaw, Will buy a MPU6050 , And plan to just mount it to the base of the stick.


Miz, I got two of this MPU6050 from eBay.

The UNO does not have enough serial ports, so I got this Arduino Mega compatible from eBay.

Finally, I got this Mega prototype shield from eBay too.

The minimum you should get is 1xMPU6050 for me to help you. I don't have an UNO, but I'll try to make my code compatible to it. 

Ideally, you should get 2xMPU6050, the Mega compatible and prototype shield too. With these, the only difference with my hardware is the motor controller and motors, then we will have a good chance of getting your machine working.


----------



## quikstep (Sep 23, 2013)

Ovaltineo said:


> Miz, I got two of this MPU6050 from eBay.
> 
> The UNO does not have enough serial ports, so I got this Arduino Mega compatible from eBay.
> 
> ...


Hi Ovaltineo. I'm a newbie trying to emulate your implementation. I was planning to use the Nano v3 to drive the DIYSegway with 2x MPU6050. 1 MPU6050 will keep the tilt value while another will keep the angle of steering bar for (obviously) making right and left turns. While you've stated that both MPUs will have different addresses (0x68 & 0x69), I've not read where the part of using Arduino Mega comes in. If i'm not interested in sending my data via bluetooth, will your latest posted code work on Arduino Nano?

Thanks for the help.


----------



## Ovaltineo (Jul 18, 2013)

quikstep said:


> Hi Ovaltineo. I'm a newbie trying to emulate your implementation. I was planning to use the Nano v3 to drive the DIYSegway with 2x MPU6050. 1 MPU6050 will keep the tilt value while another will keep the angle of steering bar for (obviously) making right and left turns. While you've stated that both MPUs will have different addresses (0x68 & 0x69), I've not read where the part of using Arduino Mega comes in. If i'm not interested in sending my data via bluetooth, will your latest posted code work on Arduino Nano?


Quikstep, the current code is guaranteed to work with an Arduino Mega, and except for setPwmFrequency, will most probably work with a Nano. As it is, setPwmFrequency will only work with the Arduino Mega. You can simply delete this function for now. The only effect is that you will get a lower frequency pitch from the motors. I will modify this later to support the UNO/Nano.

What motor controllers are you using? The current code (in motor.ino) will output sign-magnitude PWM signals, not lock anti-phase PWM. I have specifically tested it on BTN7960 motor controllers. I will modify this to support the Roboclaw.


----------



## Ovaltineo (Jul 18, 2013)

phaedrus said:


> Other than comment out the PWM frequency setting (which the compiler objected to)


P, I suspect you were not using an Arduino Mega? I think TCCR3B and TCCR4B are only available on the ATmega CPUs.


----------



## phaedrus (Aug 24, 2013)

Ovaltineo said:


> except for setPwmFrequency, will most probably work with a Nano


Just to confirm that it compiles and runs ok on an Uno with this section redacted .

P.


----------



## mizlplix (May 1, 2011)

OT:

I can get a Mega, no problem, if the Uno is too limited.
The proto board too.

(I actually have a Ruggeduino. (Plus the screw terminal blocks installed)










I just ordered two of the MPU6050's.

Is the Roboclaw OK?

I also have a 12VDC voltage regulator to run the Ard board from the 24 VDC pack. That should be safe way down there.

I want to be as adaptable as I can because this is speeding up my project a TON!

Miz


----------



## phaedrus (Aug 24, 2013)

Ovaltineo said:


> P, I suspect you were not using an Arduino Mega? I think TCCR3B and TCCR4B are only available on the ATmega CPUs.


Hah, I think we were posting at the same time!

Yes, quite right. It had me puzzled at first but when I read up on the error message(s) realised your code was for a 'mega. This was with your original code that I messed with (sorry  while I was experimenting with different things. I seem to recollect there were a number of other things I had to do to make it vaguely work - but I was also using Jeff Rowberg's library so it was a real jam session. From what I read I understood the differences between the Arduino versions weren't great so no reason to believe it wouldn't work otherwise, just the odd 'fix' as needed.

With your later code simply removing the PWM section (and fixing some P & D values) meant it fired up on the Uno fine - giving the output I queried you on a few days ago. 

I've yet to put any real hardware on it but, theoretically, that's hopefully not too far away. Once I do I'll post on how it goes!

Cheers, P.


----------



## JRoque (Mar 9, 2010)

Hi all,

Great to see all the activity on the thread!

So I hooked up the RoboClaw in Packet Serial mode and wrote a small test program to see how it worked. I'm so rusty I couldn't remember how to send in byte format over the serial port.

A couple of things I discovered. First, Arduino doesn't like it when I use the hardware serial port - it fails to program over USB (serial) most of the time. Removing the TX line from the RoboClaw to the Arduino worked around the problem. I guess this makes sense since the RoboClaw keeps the lines high and whatnot.

Next, our friendly RoboClaw board executes and sustains the last serial command it received. That is great from a ucontroller load perspective in that you can do other things like reading gyros, etc and not have to feed commands to the controller. BUT... this is another risk with this board: if you lose your micro or the serial connection to the controller, it will continue to move at whatever last command it got. I would have much preferred if the controller used some sort of heartbeat signal and it decelerated to zero when the last command time-to-live had expired.

So I have the RoboClaw and will give it a try but, at least for me, the lesson learned here for next time is to either cook my own or buy a "dumb" power section that I can fully control from the micro.

OT: the RoboClaw has two drive modes/commands: a 0 to 127 range for backward or forward or a single "drive" command with 64=stopped, 0 = full reverse, and 127 = full forward. Which of these are you planning to use?

JR


----------



## quikstep (Sep 23, 2013)

Ovaltineo said:


> Quikstep, the current code is guaranteed to work with an Arduino Mega, and except for setPwmFrequency, will most probably work with a Nano. As it is, setPwmFrequency will only work with the Arduino Mega. You can simply delete this function for now. The only effect is that you will get a lower frequency pitch from the motors. I will modify this later to support the UNO/Nano.
> 
> What motor controllers are you using? The current code (in motor.ino) will output sign-magnitude PWM signals, not lock anti-phase PWM. I have specifically tested it on BTN7960 motor controllers. I will modify this to support the Roboclaw.


My controllers are some funky made-in-malaysia ones and they accept PWM signals as well as direction. https://docs.google.com/document/d/178uDa3dmoG0ZX859rWUOS2Xyafkd8hSsSET5-ZLXMYQ/edit?usp=sharing


----------



## Ovaltineo (Jul 18, 2013)

JRoque said:


> A couple of things I discovered. First, Arduino doesn't like it when I use the hardware serial port - it fails to program over USB (serial) most of the time. Removing the TX line from the RoboClaw to the Arduino worked around the problem. I guess this makes sense since the RoboClaw keeps the lines high and whatnot.


JR, are you using an UNO or Nano? That's why I don't recommend those boards. The Mega has multiple serial ports and would avoid this problem. The best solution for these boards is to use Software Serial so you don't have to use the serial port used for programming the Arduino. I will be using this library to support these boards.




JRoque said:


> Next, our friendly RoboClaw board executes and sustains the last serial command it received. That is great from a ucontroller load perspective in that you can do other things like reading gyros, etc and not have to feed commands to the controller. BUT... this is another risk with this board: if you lose your micro or the serial connection to the controller, it will continue to move at whatever last command it got. I would have much preferred if the controller used some sort of heartbeat signal and it decelerated to zero when the last command time-to-live had expired.


Can you please test the enable pin (S3) - does it work if you pull it LOW using an output pin on the Arduino? Do the motors stop when you reset the Arduino? Do the motors stop when you disconnect this connection?




JRoque said:


> So I have the RoboClaw and will give it a try but, at least for me, the lesson learned here for next time is to either cook my own or buy a "dumb" power section that I can fully control from the micro.


I originally cooked my own controllers but suffered bruises and cuts caused by glitches at high load. I finally figured out the problem after several months. I suggest two of the BTN7960 modules at $17 each, you won't learn too much about MOSFETs and motor controllers, but they are cheaper and much less painful .




JRoque said:


> OT: the RoboClaw has two drive modes/commands: a 0 to 127 range for backward or forward or a single "drive" command with 64=stopped, 0 = full reverse, and 127 = full forward. Which of these are you planning to use?


Here's the other problem with the Roboclaw -- the "full" range is only 0 to 127 in either direction. That is half of what you get (0-255) with a PWM controller like the BTN7960. It gets worse if you use the single "drive" command. Hence, I will be using the "full" range for the Roboclaw. To be fair, I will get the same resolution on the BTN7960 if I use lock anti-phase PWM (better regenerative braking) like the Roboclaw.


----------



## Ovaltineo (Jul 18, 2013)

mizlplix said:


> OT:
> 
> I can get a Mega, no problem, if the Uno is too limited.
> The proto board too.
> ...


Miz, I will try to make my code compatible with the UNO/Nano/Ruggeduino so don't get the Mega, at least not before I miserably fail .

I have already written the code to support the Roboclaw. I'm just implementing a few other options -- support either single or dual MPU6050 and quickstep's motor controllers. It get's complicated with all the possible combinations of hardware.


----------



## Ovaltineo (Jul 18, 2013)

quikstep said:


> My controllers are some funky made-in-malaysia ones and they accept PWM signals as well as direction. https://docs.google.com/document/d/178uDa3dmoG0ZX859rWUOS2Xyafkd8hSsSET5-ZLXMYQ/edit?usp=sharing


quickstep, it's not as funky as you think because it doesn't have an enable pin or any smarts like thermal and current limiting.

The current code will not work with this board which has 1 PWM pin and 1 direction pin. My current code will only work with controllers with two PWM pins. But don't worry, I will add support for your controller as well. BTW, make sure to add a pull down resistor on the PWM pin to make sure the motors stop when the Arduino is reset.


----------



## quikstep (Sep 23, 2013)

Ovaltineo said:


> quickstep, it's not as funky as you think because it doesn't have an enable pin or any smarts like thermal and current limiting.
> 
> The current code will not work with this board which has 1 PWM pin and 1 direction pin. My current code will only work with controllers with two PWM pins. But don't worry, I will add support for your controller as well. BTW, make sure to add a pull down resistor on the PWM pin to make sure the motors stop when the Arduino is reset.


You sir, delivered the first dose of good news for the day! I do hope you can help me by showing me which part is "customised". I've read largely through your codes and have identified sections for tilt-sensor and steer-sensor. Now I'm just trying to make sure both MPU6050 actually works. I2CScanner could detect only 1 and that's probably largely due to their default HEX address being 0x68.


----------



## phaedrus (Aug 24, 2013)

Ovaltineo said:


> The current code will not work with this board which has 1 PWM pin and 1 direction pin. My current code will only work with controllers with two PWM pins.


I've been away from the thread but have in the interim been able to access my machine with the code a friend and I had been messing with...

As it happens we had, theoretically, included support for different controllers (I have two different types here presently) so this section of the code may be of interest. 

I have used it with the L298 motor controller successfully, but hadn't got around to testing it with the other controller that requires the direction pin so no guarantee it will work.

Also, and most emphatically, I need to be clear that this is very much a 'work in progress' at best; it is unfinished and isn't working properly in a test configuration let alone a full-size machine. I offer it here simply so that others may pick bits out of it (and/or laugh or curse as the case may be ). It uses quite a bit of Ovaltineo's code, and in fact was largely an attempt to make it work with the Uno and consolidate the code into one file, also we were experimenting with the MPU6050 in general. The good bits should certainly be credited to OT, we'll take the flak for the rest!

FYI the MPU6050 library used is Jeff Rowbergs offering (without modification), the code compiles and runs on an Uno, and works with the L298 motor controller and an old VCR motor attached to that as a test but 'runs away' and doesn't respond to change of board angle quite as it should. We've done nothing more on it since then but will probably get back to it in time... however I would recommend OT's latest code for those that are looking for something that has been proved to work, and a much more polished offering 

Cheers, P.

Tailpiece - the forum objected to the length of the post with the code included so I'll post it separately..


----------



## phaedrus (Aug 24, 2013)

============ Begin code from previous post ===============

/*
Segway Clone by "Ovaltineo"
Heavily modified by Phaedrus & RR Aug & Sept 2013

Original MPU-6050 routines from arduino.cc user "Krodal", now using Jeff Rowberg's

*/

// Phaedrus-----------------------------------------from 'h' file-----------------------------

#define STEER_MULTIPLIER 3 // adjust depending on your motor speed
#define MAX_ANGLE 18 // adjust depending on your board
#define MIN_ANGLE -15 // adjust depending on your board

//-------------------------------------------------------------------------------------
// PWM pins for motor

#define TWO_PIN_DRIVE true

#define RIGHT_BACKWARD_PIN 10
#define RIGHT_FORWARD_PIN 11
#define LEFT_BACKWARD_PIN 5
#define LEFT_FORWARD_PIN 6

#define LEFT_PWM_DRIVE_PIN 5
#define RIGHT_PWM_DRIVE_PIN 6
#define LEFT_DIRECTION_PIN 3
#define RIGHT_DIRECTION_PIN 4
/*
// PWM frequency selector
#define HZ_31250 1
#define HZ_3906 2
#define HZ_488 3
#define HZ_122 4
#define HZ_30 5
*/
#define MOTOR_MAX 250

//-------------------------------------------------

#include "I2Cdev.h"
#include "MPU6050.h"
#include "Wire.h"

// ----------- MPU6050 setup ---------------------

MPU6050 accelgyro;

static int16_t ax, ay, az;
static int16_t gx, gy, gz;
static float TAU = 0.96;
#define ACC_FILTER 0.05


float complementaryFilter(float accel, float gyro, long micros)
{
static float filtered_board_accel = 0;
static float angle = 0;

// filtered_board_accel = lowpassFilter(filtered_board_accel, accel, ACC_FILTER);

filtered_board_accel =((1.0-ACC_FILTER) * filtered_board_accel + (accel * ACC_FILTER));
angle = TAU * (angle + (gyro * micros/1000000.0));
angle += (1-TAU) * filtered_board_accel;

return angle;
}




void setup()
{
Serial.begin(38400); // initialize serial port (for debugging output)
Wire.begin(); // initialize I2C

accelgyro.initialize();

if (TWO_PIN_DRIVE)
{
pinMode(LEFT_BACKWARD_PIN, OUTPUT); // set left motor pin to output
 pinMode(LEFT_FORWARD_PIN, OUTPUT); // set left motor pin to output
pinMode(RIGHT_BACKWARD_PIN, OUTPUT); // set right motor pin to output
pinMode(RIGHT_FORWARD_PIN, OUTPUT); // set right motor pin to output
analogWrite(LEFT_FORWARD_PIN, 0); // stop left motor
analogWrite(LEFT_BACKWARD_PIN, 0); // stop left motor
analogWrite(RIGHT_FORWARD_PIN, 0); // stop right motor
analogWrite(RIGHT_BACKWARD_PIN, 0); // stop right motor
}
else
{ 
pinMode(LEFT_PWM_DRIVE_PIN, OUTPUT);
pinMode(RIGHT_PWM_DRIVE_PIN, OUTPUT);
pinMode(LEFT_DIRECTION_PIN, OUTPUT);
pinMode(RIGHT_DIRECTION_PIN, OUTPUT);

analogWrite(LEFT_PWM_DRIVE_PIN, 0);
analogWrite(RIGHT_PWM_DRIVE_PIN, 0);
digitalWrite(LEFT_DIRECTION_PIN, 0);
digitalWrite(RIGHT_DIRECTION_PIN, 0);
} 

delay(2000); // give sensors a couple of seconds to stabilize
}


static float gyro = 0.0;
static float accel = 0.0;

static unsigned long currMicros = 0; //The static keyword is used to create variables that are visible to only one function. However unlike local variables that get created and destroyed every time a function is called, static variables persist beyond the function call, preserving their data between function calls. 
static unsigned long pastMicros = 0; // unsigned means it can't store negative numbers
static unsigned long dt = 0; // long means(32 bit)- unsigned number from 0-4,294,967,295

static float board_angle = 0; // Float means (32 bit)- signed number from -3.4028235E38 to 3.4028235E38 (note dec pnt)
static float steer_angle = 0;
static float integral_angle = 0;
static float motor = 0;

static float P = 0.7;
static float D = 0.3;
static float I = 0.01;


void loop()
{
float board_accel;
float board_gyro;
float speed_adjust;
float steer;
int left_motor;
int right_motor;
float filtered_board_accel;
float filtered_angle;

currMicros = micros();

dt = currMicros-pastMicros; // calculate time difference in microseconds since last spin round

if (dt >= 100000) // check if 10000 microseconds (10 milliseconds) has elapsed
{
accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
pastMicros = currMicros; // reset timer

board_accel = atan((float)ax/(float)az) * 180.0 / PI + 6.0; // perceived direction of acceleration, 6.0 degree offet for specific accel
board_gyro = (gy/131.0) + 2.6; // convert to +/- 250 degrees/sec, 2.6 degree offset for this specific gyro


board_angle = complementaryFilter(board_accel, board_gyro, dt); // compute estimated true board angle


// compute speed adjustment using PID routine

integral_angle += board_angle;
speed_adjust = (P * board_angle) + (D * gyro) ;// + (I * integral_angle);

// speed_adjust = board_angle;

motor = motor + (speed_adjust);

if (motor <=-MOTOR_MAX) motor = -MOTOR_MAX;
if (motor >=MOTOR_MAX) motor = MOTOR_MAX;

// steer_angle = getSteerAngle(); // get steering angle
// steer = steer_angle * STEER_MULTIPLIER;

left_motor = motor + steer; // add steering offset to left motor
right_motor = motor - steer; // subtract steering offset from right motor



// control left and right motors

if (left_motor <= -MOTOR_MAX) left_motor = -MOTOR_MAX;
else if (left_motor >= MOTOR_MAX) left_motor = MOTOR_MAX;

if (right_motor <= -MOTOR_MAX) right_motor = -MOTOR_MAX;
else if (right_motor >= MOTOR_MAX) right_motor = MOTOR_MAX;


if (TWO_PIN_DRIVE)
{ 

if (left_motor<0) 
{
analogWrite(LEFT_FORWARD_PIN, 0);
analogWrite(LEFT_BACKWARD_PIN, -left_motor);
}
else
{
analogWrite(LEFT_BACKWARD_PIN, 0);
analogWrite(LEFT_FORWARD_PIN, left_motor);
}

if (right_motor<0) 
{
analogWrite(RIGHT_FORWARD_PIN, 0);
analogWrite(RIGHT_BACKWARD_PIN, -right_motor);
}
else
{
analogWrite(RIGHT_BACKWARD_PIN, 0);
analogWrite(RIGHT_FORWARD_PIN, right_motor);
}
}
else
{
if (left_motor<0) 
{
analogWrite(LEFT_PWM_DRIVE_PIN, -left_motor);
analogWrite(LEFT_DIRECTION_PIN, 0); // reverse
}
else
{
analogWrite(LEFT_PWM_DRIVE_PIN, left_motor);
analogWrite(LEFT_DIRECTION_PIN, 1); // forward
}

if (right_motor<0) 
{
analogWrite(RIGHT_PWM_DRIVE_PIN, -right_motor);
analogWrite(RIGHT_DIRECTION_PIN, 0); // reverse
}
else
{
analogWrite(RIGHT_PWM_DRIVE_PIN,right_motor);
analogWrite(RIGHT_DIRECTION_PIN, 1); // forward
}

}


Serial.print(micros()-pastMicros); Serial.print("\t");

Serial.print(board_accel); Serial.print("\t");
Serial.print(board_gyro); Serial.print("\t");
Serial.print(board_angle); Serial.print("\t");
Serial.print(speed_adjust); Serial.print("\t");
Serial.print(motor); Serial.print("\t");


Serial.println();

}




// Serial.print(board_accel);Serial.print("\t");Serial.print(board_gyro);Serial.print("\t");Serial.print(board_angle);Serial.print("\t");Serial.print(speed_adjust);Serial.print("\t");
// Serial.println(motor);
}


----------



## JRoque (Mar 9, 2010)

Ovaltineo said:


> JR, are you using an UNO or Nano?


Uno, same as Miz. I'll pick a pair of pins and use software serial or program the chip with and external programmer.



Ovaltineo said:


> Can you please test the enable pin (S3) - does it work if you pull it LOW using an output pin on the Arduino? Do the motors stop when you reset the Arduino? Do the motors stop when you disconnect this connection?


Results: If I pull it low it stops the controller. "Stop" is a misnomer, it really crashes the whole damn thing into a dead end and the only way to get out of "stop" mode is to power cycle the board. Yep, another gem of a feature. To me "e-stop" is worthless and won't work as a general enable/disable.

The motors do NOT stop when I reset or remove the Arduino. The e-stop pin is internally pulled up.



Ovaltineo said:


> I originally cooked my own controllers but suffered bruises and cuts caused by glitches at high load. I finally figured out the problem after several months. I suggest two of the BTN7960 modules at $17 each, you won't learn too much about MOSFETs and motor controllers, but they are cheaper and much less painful .


I've done my share of FET (and other) power sections but I wanted a quick off-the-shelf solution. I balked at the $140 price tag but I needed a controller quickly and didn't want to spend too much time fiddling with design, PCBs, etc. 



Ovaltineo said:


> Here's the other problem with the Roboclaw -- the "full" range is only 0 to 127 in either direction. That is half of what you get (0-255) with a PWM controller like the BTN7960. It gets worse if you use the single "drive" command. Hence, I will be using the "full" range for the Roboclaw. To be fair, I will get the same resolution on the BTN7960 if I use lock anti-phase PWM (better regenerative braking) like the Roboclaw.


You got it! I was pointing that out in a previous post and it's just not for the serial mode. The analog and RC mode as just as bad. RC may be a tad better but, why? Why they don't make the digital modes to be a larger range?

Here's another thing I will test next. There's a command for forward and a different command for reverse. What happens if I issue a forward=100, followed by a reverse=100? Do I have to bring forward to 0 before I issue a reserve command or will it supersede the previous motion command? The coding for that will be interesting since I'll likely end up with one of each subroutines for: fwd ramp up, fwd ramp down, rev ramp up, rev ramp down for each of the two motors. Plus the "make sure fwd is 0 before moving in rev", etc, etc.

That's enough rant. Now for the good part of the RoboClaw. I submitted my test results for analog mode and they've confirmed there's a bug in there that causes the erratic behavior. They will be sending me a new board and I'll return the one I now have. Just in time for when I no longer need analog mode 

JR


----------



## Ovaltineo (Jul 18, 2013)

JRoque said:


> Results: If I pull it low it stops the controller. "Stop" is a misnomer, it really crashes the whole damn thing into a dead end and the only way to get out of "stop" mode is to power cycle the board. Yep, another gem of a feature. To me "e-stop" is worthless and won't work as a general enable/disable.
> 
> The motors do NOT stop when I reset or remove the Arduino. The e-stop pin is internally pulled up.


Looks like I misread the Roboclaw specification document. It says "S3 is active when pulled low. It is internally pull [sic] up so it will not accidentally trip when left floating." I thought this meant that pulling S3 LOW will enable the Roboclaw and letting it float will stop it -- from a safety perspective, that would make sense. But it looks like safety is the last thing on the Roboclaw designer's mind . Now I understand why the diagrams in the Roboclaw document leave S3 unconnected.

OK, I will still toggle an enable pin for the Roboclaw. But Miz and JR (and anybody else unfortunate enough to buy this abomination) should connect this enable pin to a relay or P-channel MOSFET that toggles the power pin on the Roboclaw.


----------



## Ovaltineo (Jul 18, 2013)

phaedrus said:


> board_accel = atan((float)ax/(float)az) * 180.0 / PI + 6.0; // perceived direction of acceleration, 6.0 degree offet for specific accel
> board_gyro = (gy/131.0) + 2.6; // convert to +/- 250 degrees/sec, 2.6 degree offset for this specific gyro
> 
> 
> }


If it is still unclear from the comment, anyone using this code should replace 6.0 and 2.6 with values specific for their sensor installation. These values are the level zero-value offsets inherent to this specific installation of the sensor. A calibration routine that works this out for you would have been handy.

phaedrus, 6.0 deg and 2.6 deg/sec looks high BTW -- did you work out these values or just copied them from someone else's code?


----------



## Ovaltineo (Jul 18, 2013)

quikstep said:


> I2CScanner could detect only 1 and that's probably largely due to their default HEX address being 0x68.


quickstep, connect AD0 to VCC on the steer sensor to change the address to 0x69.


----------



## phaedrus (Aug 24, 2013)

Ovaltineo said:


> If it is still unclear from the comment, anyone using this code should replace 6.0 and 2.6 with values specific for their sensor installation. These values are the level zero-value offsets inherent to this specific installation of the sensor. A calibration routine that works this out for you would have been handy.
> 
> phaedrus, 6.0 deg and 2.6 deg/sec looks high BTW -- did you work out these values or just copied them from someone else's code?


Yes, auto-calibration of some sort would come in time, this was just a 'get something working' mess around.

Indeed the 6 & 2.6 values are worked out for what I was doing at the time, it's almost certain another installation would have different values (relatively simple to determine), but the basic calcs here should be ok - certainly the outputs from it appear as they should.

Given the detail going back and forth I'm pleased I didn't get one of these 'smart' controllers to trial, my primary unit will simply use discrete FET's in an H-bridge configuration and a couple of IC's or so to drive them. Thus (shorted FET's notwithstanding, OT!) if there's any screw-up it'll be due to the Arduino itself, or more likely something in the code .

Cheers, P.


----------



## mizlplix (May 1, 2011)

I am not using an Uno. I am using a "Ruggeduino". A Ruggeduino is a copy of an Unu-SMD, not a standard Uno. It differs in the CPU, it uses an ATMega328P SMD main processor and a ATMega16U2 USB controller.

In my perfect world, I have powered the "Duino" directly from the pack through a 12VDC regulator (Maybe that is low enough so pack sag and any ripples will not affect it so much.) 

The Ruggeduino is good for 7-24 volts input, more that a standard Uno. 12VDC seems a good place to be.

If the Duino was powered by the claw thru the S1 center pin, that could lead to several issues....I would best avoid.

My plan was to have the Main pack switch power up the Duino thru the VIN port, Use only two wires on each (S1 & S2). then I can turn on the power to the Claw after the Duino boots. 
Hopefully avoiding a run-a-way. 

It will only balance until you step onto both foot switches, Then allowing forward/rearward movement. If you fall off, it stops in place. 

Add a kill button up on the handlebars maybe.

Still too soon to tell.

Miz ( if the claw gets to be a big deal, I am able to buy something else. the claw can be donated to my grandson's robot project, it is RC controlled).


----------



## Ovaltineo (Jul 18, 2013)

Guys, you can now find the latest release of my code here. Please test and give me your feedback.


----------



## mizlplix (May 1, 2011)

Feedback: Tried to Verify, but it went about 20 lines and decided it didn't like the KP term, it wanted a value, So I gave it a "00" to get it to go on.

It went another 7 lines and didn't like KI, it wanted a value, so it too got a "00".


It went another 6 lines and didn't like KD, it too got "00"

It then went 12 lines to stop when it complained that "ACC_FILTER" was not declared in this scope. What do I temporarily stick in there to let it pass on?

I know these will be filled in later, but I would like to get it to verify at least all the way through in the mean time.
THEN stick in the gyro part, then the claw stuff. 

That is the only way I know how to keep it straight. A bit at a time.

Thx, Miz


----------



## phaedrus (Aug 24, 2013)

FYI I have all the files from OT in one directory named 'segwayclone', and the mpu6050.h file in the mpu6050 library directory (and in my case with other MPU libraries renamed so they don't cause grief...)

P.


----------



## mizlplix (May 1, 2011)

I have copied the main code into the arduino client on my computer. It has a verify button at the top under the sketch tab. 

That is supposed to check and tell if it will run. It is finding these little problems. I have not as yet had it run completely through, meaning it will not allow it to be loaded to the arduino board.


I am running a Ruggeduino. It is a copy of an Uno-SMD.


I am like a blind man looking for a sandwich and finding it has not been made.


I know the ingredients and will eventually prevail, but it will be long and difficult if at all possible.


Miz


----------



## phaedrus (Aug 24, 2013)

These things can be very frustrating at times I know. However in this case I'm sure it will work, even if it takes a little time to sort out.

I'm no expert with Arduino's - they're a relatively new thing to me - but happy to make some suggestions as to what you could try in order to replicate what I have (which appears to work)... Please excuse me if I'm telling you something you already know!



Check you're running v 1.05 of the Arduino software, if not upgrade it.
You should have an 'Arduino' directory, probably under 'My Documents'.
In this create a 'segwayclone' directory and put in that the nine files from OT's zipped archive.
The 'Arduino' directory should also contain a 'libraries' directory - that in turn should have a 'MPU6050' directory, if not then create it. Move any existing files from the MPU6050 directory somewhere else.
Copy the 'mpu6050.h' file from the 'segwayclone' directory to the MPU6050 directory.
Then try and run segwayclone.ino (should bring up the Arduino IDE).
Edit the 'motors.ino' file to remove reference to PWM as previously explained. ****** SEE NEXT POST
Tick the big tick and it *should* compile without error. If it compiles then it should be uploadable (although there's a few things to do before going too far there, like the calibrate procedure etc).

It'll be interesting to see if that works, probably there's an even easier way, but I reckon this is worth a crack to start with...

Cheers, P.


----------



## Ovaltineo (Jul 18, 2013)

What version of the Arduino compiler are you guys using? I have loaded SegwayClone.ino with both Arduino Uno and Arduino Mega as targets and get no errors at all. I have tested this on the Arduino compiler v1.0.2 and the latest v1.0.5. Please update your compiler if using an older version.


----------



## phaedrus (Aug 24, 2013)

Miz: Sorry but I found I was still compiling OT's older code - the V2 doesn't require modification to the motors.ino file, it 'just works' 

In all other respects I'd follow the steps through - it works ok for me this way.

OT: I'm using 1.05 and agree it compiles fine for me.

Cheers, P.


----------



## Ovaltineo (Jul 18, 2013)

mizlplix said:


> Feedback: Tried to Verify, but it went about 20 lines and decided it didn't like the KP term, it wanted a value, So I gave it a "00" to get it to go on.
> 
> It went another 7 lines and didn't like KI, it wanted a value, so it too got a "00".
> 
> ...


If you look at SegwayClone.h, which is included in SegwayClone.ino, you'll see that all those constants are defined, so it doesn't make sense that the compiler can't find them .


----------



## Ovaltineo (Jul 18, 2013)

phaedrus said:


> In this create a 'segwayclone' directory and put in that the nine files from OT's zipped archive.
> The 'Arduino' directory should also contain a 'libraries' directory - that in turn should have a 'MPU6050' directory, if not then create it. Move any existing files from the MPU6050 directory somewhere else.
> Copy the 'mpu6050.h' file from the 'segwayclone' directory to the MPU6050 directory.
> Then try and run segwayclone.ino (should bring up the Arduino IDE).
> ...


You shouldn't need to create an MPU6050 library. The following should work:
1. Upgrade to Arduino v1.0.5, if required.
2. Unzip SegwayClone_vX.Y.zip. This should extract a directory called SegwayClone.
3. Load SegwayClone.ino into the Arduino IDE. This will load all the modules in the SegwayClone directory.
4. Compile/Verify.


----------



## phaedrus (Aug 24, 2013)

> You shouldn't need to create an MPU6050 library.


Yes, I think it's 'cos I still had vestiges of Jeff's MPU library floating around that I needed to do this...

P.


----------



## mizlplix (May 1, 2011)

I have version 1.0.5 of the compiler.

I expected those three values to be needed and just placed a token number in them for now.

This one has me:










I am not giving up.

It will take me a while to brush back up on the terms and their meanings before I can remedy the issues.

Miz


----------



## Ovaltineo (Jul 18, 2013)

Miz, is there a SegwayClone.h in the SegwayClone directory? Can you please post the contents of this file?


----------



## JRoque (Mar 9, 2010)

Hi all.

OT: stop the presses! I just got an email from RoboClaw support and they have good news: serial commands 32 and 33 let us tap into their PWM input range of -1500 to +1500 for reverse/forward speeds. The commands are buried in the "encoder" section of the manual (pg 45) so I skipped it. However, it does say "encoders not required" next to them. Doh!

I suggested a timeout so motors stop if no input is received in that time. They are working on adding just that to the serial mode and already have it in the current firmware for RC mode. 

I think the solution for us here is to use commands 32/33 and the signed input for each of the motors using two byte data. I'm going to prototype that and see how it works.

JR


----------



## mizlplix (May 1, 2011)

Awesome, JR!

The DIY file attachment uploader will not let me upload the files. It says "Invalid file" for both the SegwayClone and the SegwayClone H file.
they BOTH are straight from your download link....unmodified.

An Error Has Occurred!
SegwayClone.ino.
You cannot upload that type of file. The only allowed extensions are doc,gif,jpg,mpg,pdf,png,txt,zip.

I really love the whole windows system. 

I guess I will have to zip it up then...GRRRRRR!

"You can't get there from here" has a whole new meaning....

Miz


----------



## Ovaltineo (Jul 18, 2013)

Miz,
Are you using "Sketch - Add File..." to open SegwayClone.ino? You should use "File - Open..."!


----------



## JRoque (Mar 9, 2010)

Hi all.

I think Miz was referring to issues attaching a file to this forum, not uploading it in the Arduino environment.

Ok so I can confirm command #32 (and #33 for motor #2) works as expected. The command packet is composed like this:

Address, Command, HighByte, LowByte, Checksum

Address will likely always be 128 since we only have 1 of these controllers per segway. Command is 32 for motor 1 and 33 for motor 2. Speed ranges from -1500 to +1500, split into 2 signed bytes as shown above. Add all those values plus an 8th bit mask and that's your checksum.

Commands #52 and #53 have provision to set acceleration as well, if we were to need that sort of thing. You can set speed and accel (from 0 to 65535) in the same command. I suspect in this application we will need max acceleration rate only to keep a steady balance.

JR


----------



## phaedrus (Aug 24, 2013)

JR: Good news for you guys!

Miz: Did you confirm all those nine files are in one directory, and did you click on the 'segwayclone.ino' file to run it? 

If you do this (ie. click & open segwayclone.ino from windows explorer) it should bring up it up with all the associated files in the IDE, and from there it should compile. Check across the IDE tabs that it shows "SegwayClone, EEPROM.h, EEPROM, MPU6050.h, MPU6050, Motors.h, Motors, SegwayClone.h" in a row just under where the tick & arrow icons are...

In terms of posting the contents of SegwayClone.h for OT you could just go to that tab in the IDE & copy/paste to the forum - I realise the formatting here will mess it up a little but by doing this you'll confirm first of all that the compiler has the file and it's contents, and OT will get to see for sure what's in it 

Cheers, P.


----------



## Ovaltineo (Jul 18, 2013)

I have updated the code (now v2.1) to use the -1500. to 1500 range for the Roboclaw. I thnk you need to significantly increase the P and D values for that.

I have also changed the PWM pins for non-Mega boards because pin 2 is not a PWM pin, plus I am now setting the PWM frequency for pins 9 & 10 and 3 & 11.
Latest code can be found in the same place.


----------



## JRoque (Mar 9, 2010)

Hi.

Ok OT I downloaded and compiled your code, thanks! Had to insert an

```
#include <I2Cdev.h>
```
 statement in there since it wouldn't find that reference off of my existing MPU6050 library.

But it compiles and I sent it to the board. I see a bunch of "Gyro" + numbers scrolling by, ending the list with something like: X Accel Offset -5190Y Gyro Offset 93Y Gyro Min -98Y Gyro Max 348. Whatever that means 

I have only one MPU so I used MPU6050_X1_STEERING, plus ROBOCLAW_CONTROLLER. The motors don't move at any point, even if I move the sensor board.

Keep in mind that I know nothing about Arduino. This is the second time ever that I send code to the board using the Arduino UI/compiler. So with that clear: where do you set the soft-serial baud rate? Is it set to 38400, which is the max the RoboClaw accepts? Or does the soft-serial follow whatever you set on the hardware serial?

JR


----------



## Ovaltineo (Jul 18, 2013)

JR, you have compiled and run in MODE_CALIBRATE, hence it will print all those samples, take the average, save the calibration data to EEPROM, and halt. You now need to comment out or delete #define MODE_CALIBRATE, compile and upload. This time, it will wait for you to level the board at +-2 degrees, then it will start balancing on its own.


----------



## mizlplix (May 1, 2011)

I kind of feel like the caveman who needed to mine the ore, smelt the ore, to make a pick-axe. BUT, needs the pick-axe to mine the ore in the first place.....
So .......

In your version 2 file, I went and downloaded it. 

It was one file: SegwayClone

Unzipped it and opened it into 7 files:

Motors.h

EEPROM.ino

EEPROM.h

SegwayClone2.ino

MPU6050.ino

MPU6050.h

Motors.ino

They are now sitting on my desktop in the SegwayClone folder.

Yes I was using ""Sketch - Add File..."

Yes, I was referring to uploading to the forum. I have no troubles with the compiler except I ALWAYS get some kind of unresolved issue and the sketch will not verify. Plus I am not adverse enough to even understand what it wants....which leads to frustration.

Example: I was glad to get your code file. When opened, it puzzled me that it was not one file, but seven files. I had no idea what to do with seven files, when I only needed one...

Also, why is there two files: One with ino suffix and one with h suffix? See, helpless.


This is like taking Spanish in the 6th grade. The teacher would not let us ask a question in class unless you spoke spanish...

Guess what? most of the class failed. 

Miz


----------



## mizlplix (May 1, 2011)

When I open SegwayClone2.ino in the arduino client I get:


/*
Segway* Clone by "Ovaltineo" for Arduino

*Segway is a trademark of Segway Inc.

Copyright (C) 2013 Carmelo Porciuncula

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

This program includes MPU-6050 routines from arduino.cc user "Krodal".

See the README for instructions.

*/

#include <Wire.h>
#include "SegwayClone.h"

static unsigned long currMicros = 0;
static unsigned long pastMicros = 0;
static unsigned long dt;
static float board_angle = 0;
static float steer_angle = 0;
static float integral_angle = 0;
static float motor = 0;
static float Pf, If, Df;
static boolean waitForLevel;
static int loopcount = 0;

float getP()
{
//int Pv = analogRead(A0);	// read P potentiometer
//return (.8 * Pv/1023);	// range 0 to 0.8

return KP; // return static value
}

float getI()
{
//int Iv = analogRead(A1);	// read I potentiometer
//return (.05 * Iv/1023); // range 0 to 0.05 

return KI; // return static value
}

float getD()
{
//int Dv = analogRead(A2);	// read D potentiometer
//return (.5 * Dv/1023);	// range 0 to 0.5

return KD; // return static value
}

float complementaryFilter(float accel, float gyro, long micros)
{
static float filtered_board_accel = 0;
static float angle = 0;

filtered_board_accel = lowpassFilter(filtered_board_accel, accel, ACC_FILTER);
angle = TAU * (angle + (gyro * micros/1000000.0));
angle += (1-TAU) * filtered_board_accel;

return angle;
}

float computePID(float angle, float gyro)
{
float result;

integral_angle += angle;
result = ((Pf * angle) + (If * integral_angle) + (Df * gyro));
return result;
}

#ifdef POT_STEERING
/* Use the following if using a potentiometer for the steering.
This assumes pot is on A3 pin and center returns 512, full left returns 0, and full right returns 1023.
*/
float getSteerAngle(void)
{
int pot = analogRead(A3);	// read D potentiometer, range is 0 to 1023
pot = pot - 512; // range is now -512 to +511
return (pot*240/1023); // convert to degrees (assumes pot has 240 degree sweep)
}
#else

/* Use the following if using an accelerometer for the steering.
*/
float getSteerAngle(void)
{
static float filtered_steer_accel = 0;
float steer_accel;


steer_accel = getSteerAccel();
filtered_steer_accel = lowpassFilter(filtered_steer_accel, steer_accel, ACC_FILTER);
return filtered_steer_accel;
}
#endif

void buzzer(float on)
{
if (on)
digitalWrite(BUZZER_PIN, HIGH);
else
digitalWrite(BUZZER_PIN, LOW);
}

void setup()
{
Serial.begin(115200); // initialize serial port (for debugging output)
Wire.begin(); // initialize I2C
pinMode(BUZZER_PIN, OUTPUT);	// set buzzer pin as output
digitalWrite(BUZZER_PIN, LOW);	// turn off buzzer

initMotors(); // initialize the motors
delay(2000); // give sensors a couple of seconds to stabilize

buzzer(true); // turn on buzzer
delay(1000); // wait 1 second
buzzer(false); // turn off buzzer
#ifdef MODE_CALIBRATE
initBoardSensor(CALIBRATE_YES); // initialize board tilt sensor and calibrate
#ifndef POT_STEERING
initSteerSensor(CALIBRATE_YES); // initialize steering tilt sensor and calibrate
#endif
#else
initBoardSensor(CALIBRATE_NO); // initialize board tilt sensor
#ifndef POT_STEERING
initSteerSensor(CALIBRATE_NO); // initialize steering tilt sensor
#endif
#endif

Pf = getP(); // get P value
If = getI(); // get I value
Df = getD(); // get D value

waitForLevel = true;	// set flag to wait for board to level
buzzer(true); // turn on buzzer to indicate board is waiting to level, or end of calibration
}

void loop()
{
#ifndef MODE_CALIBRATE
float board_accel;
float board_gyro;
float speed_adjust;
float steer;
int left_motor;
int right_motor;

currMicros = micros();

dt = currMicros-pastMicros;

if (dt >= 10000) // check if 10000 microseconds (10 milliseconds) has elapsed
{
pastMicros = currMicros; // reset timer
board_accel = getBoardAccel();	// get board accelerometer value
board_gyro = getBoardGyro();	// get board gyro value
board_angle = complementaryFilter(board_accel, board_gyro, dt);	// compute board angle
if (waitForLevel)	// check if we need to wait for board to level
{
if (board_angle > -2 && board_angle < 2)	// check if board is sort of level (+/- 2 degrees)
{
waitForLevel = false;	// set flag to indicate board has been levelled
motor = 0; // make sure motor is reset to zero
integral_angle = 0; // make sure integral angle is reset to zero
buzzer(false); // turn off buzzer
}
}
else
{
speed_adjust = computePID(board_angle, board_gyro); // compute speed adjustment using PID routine
motor = motor + speed_adjust;

if (motor > 255)
motor = 255;
else if (motor < -255)
motor = -255;


steer_angle = getSteerAngle(); // get steering angle
steer = steer_angle * STEER_MULTIPLIER;

left_motor = motor - steer; // add steering offset to left motor
right_motor = motor + steer; // subtract steering offset from right motor

if (left_motor > 255)
left_motor = 255;
else if (left_motor < -255)
left_motor = -255;

if (right_motor > 255)
right_motor = 255;
else if (right_motor < -255)
right_motor = -255;

if (board_angle < MIN_ANGLE || board_angle > MAX_ANGLE ) // stop motors if over-angle
{
left_motor = 0;
right_motor = 0;
buzzer(true); // turn on buzzer to indicate board is waiting to level
waitForLevel = true;	// set flag to wait for board to level
}

loopcount++;
if (loopcount==20) 
{
loopcount = 0;
Serial.print(F(" ACCEL: ")); 
Serial.print(board_accel);
Serial.print(F(" GYRO: ")); 
Serial.print(board_gyro);
Serial.print(F(" ANGLE: ")); 
Serial.print(board_angle);
Serial.print(F(" MOTOR: ")); 
Serial.print(motor); 
Serial.print(F(" LEFT: ")); 
Serial.print(left_motor); 
Serial.print(F(" RIGHT: ")); 
Serial.println(right_motor); 
}

controlMotors(left_motor, right_motor); // control left and right motors
}
}
#endif
}

I also have 8 tabs across the top. (this one and 7 more)

And it compiles perfectly. (the first one I have ever run perfectly, except a simple 8 line sample)

I will try to upload it to my board.

(fingers crossed)

Miz


----------



## quikstep (Sep 23, 2013)

hey mizlplix,

what i did was;
in sketch, File > Open, then Navigate to the unzipped SegwayClone folder and select SegwayClone.ino

it will by default open up the rest of the 6 files. if you have MPU6050 folder in your libraries, just relocate MPU6050 folder out of the libraries folder before you verify/upload.


----------



## Ovaltineo (Jul 18, 2013)

Miz, 

Congratulations! It was a challenge to get there, but we got there . Please look at post #181 and make sure you read the README file in full. It explains that you need to set and unset calibrate mode to get some sort of balancing happening with your machine. I think you also need to change KP and KD to a much higher value for the Roboclaw, but give it a test the way it is first.


----------



## JRoque (Mar 9, 2010)

Hello.

Thanks OT for the tips. I took the CAL parm out and recompiled. I can see something like this scrolling by:


```
ACCEL: 2.28 GYRO: 0.78 ANGLE: 2.51 MOTOR: 255.00 LEFT: 254 RIGHT: 255
 ACCEL: 2.45 GYRO: 0.76 ANGLE: 2.51 MOTOR: 255.00 LEFT: 254 RIGHT: 255
 ACCEL: 2.34 GYRO: 0.62 ANGLE: 2.51 MOTOR: 255.00 LEFT: 254 RIGHT: 255
 ACCEL: 2.20 GYRO: 0.62 ANGLE: 2.51 MOTOR: 255.00 LEFT: 254 RIGHT: 255
 ACCEL: 2.39 GYRO: 0.66 ANGLE: 2.50 MOTOR: 255.00 LEFT: 254 RIGHT: 255
 ACCEL: 2.38 GYRO: 0.63 ANGLE: 2.50 MOTOR: 255.00 LEFT: 254 RIGHT: 255
```
I don't have a buzzer on my board but I have tilted the gyro under 2 deg to see if the motors start after that.

A couple of questions. On this section, shouldn't it say something other than "MEGA"? I commented that "if/then" statement out for a try.


```
#ifdef ROBOCLAW_CONTROLLER
    #define MOTOR_MAX        1500
    #define ROBOCLAW_ADDRESS 0x80

    // ROBOCLAW packet serial commands
    #define M1_SPEED    32
    #define M2_SPEED    33

    #ifndef MEGA
        // software serial pins for non-mega boards
        #define SOFT_RX_PIN    5
        #define SOFT_TX_PIN    6
    #endif
    #define MOTOR_ENABLE_PIN    7        // connect this pin to a relay or P-channel MOSFET that bridges the 
                                        // two LB-MB pins on the Roboclaw.  LB-IN must remain unconnected.
#endif
```
Also on the readme file it says pin 5 (PCINT21/OC0B/T1/PD5 on the Atmel chip) goes to S1 but, isn't S1 the RX pin on the RoboClaw? Shouldn't the TX on the Arduino go to S1?

JR


----------



## Ovaltineo (Jul 18, 2013)

JRoque said:


> A couple of questions. On this section, shouldn't it say something other than "MEGA"? I commented that "if/then" statement out for a try.
> 
> 
> ```
> ...


JR, you are absolutely right, I got it switched around. S1 is the RX pin and should connect to pin 6. S2 pin should connect to pin 5, although it is not yet used in the code.

"#ifndef MEGA" means include the following clause if MEGA is not defined. So, the SOFT_RX_PIN and SOFT_TX_PIN will ony be defined on non-mega boards. For mega boards, the code uses the hardware Serial1.


----------



## JRoque (Mar 9, 2010)

Hey OT, you're probably regretting publishing your code and getting all of these tech support calls 



Ovaltineo said:


> "#ifndef MEGA" means include the following clause if MEGA is not defined.


I knew that if/then statement looked funny 

Ok I can see the RoboClaw status light blink, which it does when it receives data. But the (sort of) "run" LED is not blinking. I loaded my test code and the run LED and motors run. In fact, I can leave them running and upload your code without the RoboClaw making any change (don't have the disable pin attached yet) 

I think this suggests the commands are not reaching the controller properly. Your packet build looks good so I don't understand why it won't go, assuming the data bytes are set correctly elsewhere.

I added a buzzer LED and that lights up nicely at start up so init works as expected.

JR
PS: you prefer to field these questions here or on your code thread?


----------



## mizlplix (May 1, 2011)

Yahoo!

The sketch uploaded perfectly, no issues.

I need to wait for the two New Gyros I ordered from Fleabay. They are coming from China (Where else).

I need to make note of the changes to the S1 to pin 6 and the S2 to pin 5. AND read
the "readme".....

Also: Keep in mind to alter the KP and KD values for the Roboclaw if needed.


Now for my #1 question: 

*Would you play with the small balancing robot I have built, or just install it all into the full sized Segway clone?*

I have a rack for the full sized scooter that holds the tires off of the ground.
That should make the early adjusting phase safer. 

Miz


----------



## JRoque (Mar 9, 2010)

Hey Miz,

I connected two standalone motors to the RoboClaw to see if they move first so I don't have to go back and forth to the garage until I get the basics happening.

That said, I would go for the real thing since its off the ground and you can fine tune with the whole setup. 

OT made provisions to run with a single gyro by setting #define MPU6050_X1_STEERING 

Next, you would run the code once in "calibrate" mode, allow it to save the parms to EEPROM, recompile with #define MODE_CALIBRATE commented out and flash the code again.

If you get a chance, hook up the soft-serial pins (5 & 6 plus GND) and see if you get the controller to take run commands. RoboClaw's Stat1 and Stat2 LEDs come on when a motor is running. Not sure if you have a gyro at hand to do this though.

JR


----------



## Ovaltineo (Jul 18, 2013)

JRoque said:


> Hey OT, you're probably regretting publishing your code and getting all of these tech support calls
> 
> 
> 
> ...


JR, can you post the contents of your test code please? 

Did you use v2.0 or 2.1 of my code? v2.0 is using the -127 to 127 range while v2.1 is using the -1500 to 1500 range. But looks like neither of them would work from what you are describing. I will hook up my oscilloscope to see what is coming out of pin 6.

I don't mind which thread you post the questions.


----------



## JRoque (Mar 9, 2010)

Hi OT,

I'm using v2.1 and see -255 to 255 on the "Motor" output of your debug window. Not sure if that matters.

My test code is for a different language/compiler and entirely outside the Arduino environment. But essentially, I'm setting port D.5 and D.6 as outputs, loading a software serial and sending a packet formatted pretty much like yours: 

Print #1 , cAddress ; bCommand ; bTXDataH ; bTXDataL ; bChecksum

If the scope setup is too difficult, perhaps you can pipe what's being set to pin 6 up to the hardware serial and show it in the serial monitor window. I tried it but Arduino complained - I think I would need to setup the hardware port within the same module where the software serial is being declared? Sorry I'm clueless on how Arduino works.

JR


----------



## mizlplix (May 1, 2011)

I have a really good 3 axis gyro/accel/mag but I guess it will not work with Oval's code. I don't have any guess, just what I am told.

I ordered two of what he specified. ETA 2 weeks.

I did hook up two small Pots to the S1 and S2 pins and at 0 volt they ran full back, 1 volt they stopped and 2 volts they went full forward. (In simple serial though)

Other than that, I am just awaiting the Gyros...

Miz
P.S.: I think I will transplant everything to the Scooter and be done with it. That way I only need to fine tune once.


----------



## JRoque (Mar 9, 2010)

mizlplix said:


> I did hook up two small Pots to the S1 and S2 pins and at 0 volt they ran full back, 1 volt they stopped and 2 volts they went full forward. (In simple serial though)


Did the pots control each individual motor or did one pot control both? You're probably in analog mode since serial mode requires a digital command, not an analog voltage.

JR


----------



## phaedrus (Aug 24, 2013)

mizlplix said:


> I have a really good 3 axis gyro/accel/mag but I guess it will not work with Oval's code.


Miz: The MPU6050 is probably worth the wait but what is the current board you've got again? I googled G60 (which is what you'd said at the start) and it didn't bring anything intelligent up for me...

Cheers, P.


----------



## mizlplix (May 1, 2011)

P: The board is blue. It has 10 out/inputs. It says GY-80 on it.

No other I.D.

It appears to be this one: http://dx.com/p/gy-80-bmp085-9-axis-magnetic-acceleration-gyroscope-module-for-arduino-145912

It purportedly does 9 axis gyro/accel, Baro, Temperature with compass. (analog)

It was supposed to do everything except make lunch for you.

I think analog was Oval's problem with it, He wrote code for Digital. (At least that is my rememberance)

Miz


----------



## phaedrus (Aug 24, 2013)

mizlplix said:


> P: The board is blue. It has 10 out/inputs. It says GY-80 on it.
> 
> ....
> 
> I think analog was Oval's problem with it, He wrote code for Digital. (At least that is my rememberance)


Miz, from what I read that module is I2C, not analog, and uses the ADXL345 accelerometer and L3G4200D gyro (leaving the others out for the present - not sure you need to know the elevation/direction of yer segway yet!). 

These should be usable with OT's code if you use the correct libraries for the devices and make appropriate changes in the code - as OT has said he's written his code in a fundamental way as to make such changes feasible.

I'm not necessarily advocating you do this, but if you wanted to experiment then you could have a go - you'd connect it up to the Ruggedino similarly to the MPU6050 (ie. using the gnd, pwr, scl, sda and int), include the libraries and start playing from there...

I may have something similar here, I'll look it out and see what it is once I've finished a bit more of my machine (I'll be hooking up the controller and PSU etc tomorrow preparatory to putting them in the chassis). If I can find it I'll hook it up and see what I can make of it.

Cheers, P.


----------



## Ovaltineo (Jul 18, 2013)

JRoque said:


> Hi OT,
> 
> I'm using v2.1 and see -255 to 255 on the "Motor" output of your debug window. Not sure if that matters.
> 
> ...


JR, I found the problem! It was a bit tricky to find because the signal looks good on my digital oscilloscope. As per your suggestion, I hooked it up to another Arduino and saw that data are getting dropped. I increased the cycle time from 10ms to 12.5 ms and it got fixed. So it must be a serial buffer overrun caused by the low 38400 bps max baud rate of the Roboclaw.

I also fixed the bug that caused the range to stay at -255 to 255 instead of -1500 to 1500. Actually, for safety reasons, I have now intentionally lowered the default MOTOR_MAX to -30 to 30 when using PWM and -180 to 180 when using Roboclaw. I would suggest to everyone to increase MOTOR_MAX to the full range only if everything has been tested thoroughly.

These fixes are now in V2.2 in the same place. Make sure to comment out #define MODE_CALIBRATE if you have already done the calibration phase.


----------



## Ovaltineo (Jul 18, 2013)

mizlplix said:


> P: The board is blue. It has 10 out/inputs. It says GY-80 on it.
> 
> No other I.D.
> 
> ...


Miz, I didn't know you had a GY-80. From the two source codes that you posted, I assumed that you were using an analog sensor.

The ADXL345 accelerometer and L3G4200D gyro are not as good as the MPU6050 but they're okay. I'll see if I can add support for them with my code.


----------



## phaedrus (Aug 24, 2013)

Ovaltineo said:


> The ADXL345 accelerometer and L3G4200D gyro are not as good as the MPU6050 but they're okay. I'll see if I can add support for them with my code.


After looking through my records it turns out I ordered a GY-85 at one stage so should have it around somewhere.

This uses an ADXL345 so I could probably check that out, but the gyro is a ITG3200 so can't do the L3G4200D, sorry...

If OT does add the GY-80 to his code you could be up and running fairly soon Miz 

Cheers, P.


----------



## mizlplix (May 1, 2011)

I have been putting the finishing touches on my stick centering linkage.
It is a little hard to see in these pics, bit it is modeled off of a design I remembered from somewhere. 

Stick left:









Stick right:








It is fully adjustable both for center and stiffness. I have yet to mount the end plates. There is a large range of adjustment too.

A small bracket gets welded on the base of the removable tiller tube for the Gyro board to mount. It stays inside that front compartment.

Miz


----------



## JRoque (Mar 9, 2010)

Very nice, Miz! At first view, it doesn't seem like it would have that much range but you clearly show it does. I can imagine that a strong springing back to center is not that critical since the rider will be moving it left and right a lot anyway. It is critical for calibration, however.

OT: loaded the code while forgetting to change from 2 gyros to 1 and got some motor spinning! However, moving the gyro had no effect after that. Changing it to a single gyro (I'm only using one), didn't move the motors.

So it could still be related to timing or maybe something with the vars in the packet. I wish I had more time to dive in there and take a closer look at what's being sent. Let me see if I can rig something tonight.

How about isolating it by providing a 'debug' mode where it would send a series of canned move commands at various speeds? That would confirm the packets are being sent correctly and the issue is elsewhere. Of course, easy for me to type it here and send you to do all the work 

JR


----------



## Ovaltineo (Jul 18, 2013)

JR,

Can you please test the following sketch? It should make both motors spin up and down forward and reverse like a yoyo. Watch the debug output in the serial monitor. If it doesn't work, can you please increase CYCLE_TIME in increments of 500?


```
#define CYCLE_TIME 12500

#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega1281__) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega2561__)
  #define MEGA
#endif


#ifndef MEGA
	#include <SoftwareSerial.h>
#endif


#define ROBOCLAW_ADDRESS 0x80

// ROBOCLAW packet serial commands
#define M1_SPEED	32
#define M2_SPEED	33

#ifndef MEGA
	// software serial pins for non-mega boards
	#define SOFT_RX_PIN	5			// connect to S2 pin
	#define SOFT_TX_PIN	6			// connect to S1 pin
#endif
#define MOTOR_ENABLE_PIN	7		// connect this pin to a relay or P-channel MOSFET that bridges the 
									// two LB-MB pins on the Roboclaw.  LB-IN must remain unconnected.


#ifndef MEGA
	SoftwareSerial Serial1(SOFT_RX_PIN, SOFT_TX_PIN); // RX, TX
#endif

void sendCommand(byte command, int param)
{
	byte packet[5];
	packet[0] = ROBOCLAW_ADDRESS;
	packet[1] = command;
	packet[2] = param >> 8;		// MSB
	packet[3] = param & 0xFF;	// LSB
	packet[4] = (packet[0]+packet[1]+packet[2]+packet[3]+packet[4]) & 0x7F;
	Serial1.write(packet, sizeof(packet));
}

void setSpeedMotor1(int speed)
{
	sendCommand(M1_SPEED, speed);
}

void setSpeedMotor2(int speed)
{
	sendCommand(M2_SPEED, speed);
}

void initMotors(void)
{
	Serial1.begin(38400);			// initialize serial port
	pinMode(MOTOR_ENABLE_PIN, OUTPUT);


	digitalWrite(MOTOR_ENABLE_PIN, HIGH);	// You must connect MOTOR_ENABLE_PIN to a relay or P-channel MOSFET
											// that bridges the two LB-MB pins on the Roboclaw.  LB-IN must
											// remain unconnected.
	//stop motors
	controlMotors(0, 0);
}


void controlMotors(int speedL, int speedR) {
	setSpeedMotor1(speedL);
	setSpeedMotor2(speedR);
}

void setup(void)
{
	Serial.begin(115200);
	initMotors();
}

static unsigned long currMicros = 0;
static unsigned long pastMicros = 0;
static unsigned long dt;
static int speed = 0;
static int increment = 10;
static int count = 0;

void loop()
{

	currMicros = micros();

	dt = currMicros-pastMicros;
	if (dt >= CYCLE_TIME) // check if 12500 microseconds (12.5 milliseconds) has elapsed. Needs slower rate due to 38400 bps serial
	{
		count++;
		if (count == 20)
		{
			count = 0;
			speed = speed + increment;
			if (speed == 1500)
				increment = -10;
			else if (speed == -1500)
				increment = 10;
			Serial.print("Speed = ");
			Serial.println(speed);
		}
		controlMotors(speed, speed);
	}
}
```


----------



## JRoque (Mar 9, 2010)

Hooray! I think I found the problem.

On the line below, packet(4) is being added in but it should be:


```
packet[4] = (packet[0]+packet[1]+packet[2]+packet[3]) & 0x7F;
```
I tried that on V2.1 and it worked! I must have looked at that line 20 times and missed it. It wasn't until I typed in hardcoded values on a separate serial.write line that I realized the checksum was being added to itself. In theory, it should have worked the first time because packet(4) was empty. But that state only lasted 12.5ms before it was overwritten by the corrupt packet.

Ok so we're now past that issue. Question: you have to be within 2 degrees of zero to be considered "balanced". Does that mean that there's a 2 deg hysteresis in the system and I can be up to 2 deg off kilter and the controller won't try to correct it?

Perhaps its all there and I haven't seen it yet but it would be great if the hysteresis, max tilt angle, etc are all defined at the top of the code and all together to make it easier to change and adapt.

Thanks so much for all the hard work, OT! I can almost feel the scraped knees now  I might just duct tape everything together and see how fast I can eat dirt.

JR


----------



## Ovaltineo (Jul 18, 2013)

Well done JR! There is no hysteresis in the system. The +-2 degrees from level is only used at the start so the system doesn't shoot off if you turn it on while it is lying on the ground at 90 degrees. It is also used if it goes over MAX_ANGLE.


----------



## phaedrus (Aug 24, 2013)

Miz: I really like that steering mechanism of yours - it's much tidier than the exposed spring method . 

Mind you I wonder, given that they're springs in compression, if they could be inclined to spring sideways on occasion? Anyway I guess a tube shroud over each spring would assist with that if need be.

OT: Congratulations are also due to you! I tried your new code on my hardware today and it went well... I made a few minor changes to fit my particular environment but essentially it 'worked out of the box' once the calibration was done and the reponse was good with a reasonably 'stiff' feel to it. Note this was just as a balancing platform, I've not got a complete unit with steering etc yet.

At this stage the only real comment I would have is that when it's first turned on it wants to spin the wheels for a second or two - so you need to have it jacked up for that period otherwise it takes off. I've not looked into why yet; it could be unique to my setup.

Just FYI this is using a Uno and 'dumb' PWM motor controller with direction pin.

I hope to do a bit more this week (the kids are away!) so will report on any further progress that may be of interest.

Cheers, P.


----------



## mizlplix (May 1, 2011)

The springs are SO stiff that they stay straight during compression. At rest, they only have about 1" each direction to compress.

I finally got it all finished and it is really nice...But...Never use cooler bearings that are rubber mounted. They induce a little flex in the controlls. 
While it is not worth changing, looking back, I would have bought solid ones.


Lets talk ENCODERS:

I finally got around to doing a trial fitting of the encoders on the motor brake shaft stub.

The shaft diameter is exactly the one needed to fit the encoder wheel.
The encoder wheels have an offset on one side, giving some adjust-ability.

Having said that, the stubs are VERY short. I wanted a solution where I did not have to lengthen them.

Well, it was really simple!

Do not use the plastic encoder base. It helps to locate the sensor, but it also locates on the two cover mounting screws.

Clean the shaft with paper, slip on the wheel Using the sensor for a gauge, set the wheel height and tighten the grub screw.

Locate the sensor and mark the two holes. Drill and thread the holes in the aluminum motor end housing.

Mount the sensor and cover with the two screws and tighten....done.

Make sure you orient the pin outs to coinside with the motor power leads, so they can run neatly with them. 

Make sure the encoder wires are twisted and wrapped with aluminum foil before the outer shrink sleeve.

Miz


----------



## Ovaltineo (Jul 18, 2013)

phaedrus said:


> OT: Congratulations are also due to you! I tried your new code on my hardware today and it went well... I made a few minor changes to fit my particular environment but essentially it 'worked out of the box' once the calibration was done and the reponse was good with a reasonably 'stiff' feel to it. Note this was just as a balancing platform, I've not got a complete unit with steering etc yet.
> 
> At this stage the only real comment I would have is that when it's first turned on it wants to spin the wheels for a second or two - so you need to have it jacked up for that period otherwise it takes off. I've not looked into why yet; it could be unique to my setup.
> 
> Just FYI this is using a Uno and 'dumb' PWM motor controller with direction pin.


Thanks P. You will need to play with KP and KD to get it just right. I suggest keeping KI zero -- setting it to non-zero created unexpected surges during my testing.

Did you put a pull down resistor on the PWM pin (e.g. 1K resistor to ground)? Even better, is there an enable pin on the controller? If there is, pull it down to ground with a resistor and change the initMotors routine to pull this HIGH with a digital pin.


----------



## Ovaltineo (Jul 18, 2013)

Miz, good news! I have now added support for the GY80 board in v2.3 of the code. 

When mounting the sensor, make sure that the X-axis is level and pointing to the front of the vehicle.

I found a bug in the calibration routine where the steering data is not saved. This is now fixed. Everyone should update to v2.3 and re-calibrate.

I have also added JR's fix to the Roboclaw serial packet checksum.

You can find the latest code in the same place.


----------



## phaedrus (Aug 24, 2013)

Ovaltineo said:


> Did you put a pull down resistor on the PWM pin (e.g. 1K resistor to ground)? Even better, is there an enable pin on the controller? If there is, pull it down to ground with a resistor and change the initMotors routine to pull this HIGH with a digital pin.


OT: No, I've not really pursued the reason for the unintended motor operation yet but will have a look at it this week I hope, thanks for the suggestion.

Interestingly it's changed now (by itself!) so that just one motor operates on turn on... might be a good opportunity to drag the 'scope out and see what's going on.

Good on you for including that GY-80, Miz will be pleased!

Miz: Ok on the encoders, perhaps I missed this bit (must have a look back in the thread) but are you intending on incorporating them in your design? I know a number of people have, and claim it improves their operation, but I've not really thought them necessary - unless I wanted a true speed readout or return to original position control...

Cheers, P.


----------



## Ovaltineo (Jul 18, 2013)

Encoders would significantly improve the response over hills and bumps. It should maintain a steady pace regardless of the terrain. You can also dial back the PID values so you won't get oscillations especially when there is no rider standing on the vehicle.


----------



## phaedrus (Aug 24, 2013)

Actually that's true isn't it - now that I think about it!

I've got similar motors to Miz's and guess that I could do the same, but that's probably going a bit further than I want to presently. 

From memory I think that there was quite a bit done with the Elektor code and encoders - a group of people from Germany (IIRC) seemed to be quite keen on them. I seem to recall having to translate some of the discussions, and there was some code around, but they were using Bascom. I did get part way through converting that to C but then other things got in the way..

You reminded me also to say that with my unit there was a small amount of oscillation when I ran it at 24v with no load on the platform, reducing to 12v, or loading the platform a little reduced that essentially to nothing.

Cheers, P.


----------



## Ovaltineo (Jul 18, 2013)

I found a bug in the calibration of the gyro, so please download version 2.4 from the same place and re-calibrate.


----------



## Ovaltineo (Jul 18, 2013)

Found, hopefully, the last calibration bug. Please download version 2.5 from the same place. If you already calibrated with v2.4, there is no need to re-calibrate.


----------



## mizlplix (May 1, 2011)

I just grabbed a copy of 2.5

I will work on mounting the gyro to the stick today and get this version flashed to the duino

All I need to do then is to transplant the claw and ECU to the scooter and wire it all up.

At this point, all I have in it is the pack wiring, main cut off switch and the charge plug for the pack.

The weather is just getting nice here in Arizona and working outside most of the day is possible. 

When you move from a machine shop to a three car garage, you wind up having way too much equipment. 
(Even if most is in a 53' shipping container.) I need to do a serious reorganization to get some more floor space. 

Thanks to OT for the timely code updates.

Miz


----------



## JRoque (Mar 9, 2010)

Hi all,

Here's a project update. I mounted the batteries and the rest of the electronics using some plywood (don't have a metal bender yet). The gyro is mounted at the intersection of X and Y axes.

The scooter balances itself, sort of, and rides around, again sort of. Had to reverse the left and right motors in the code as it was easier than swapping the cables. I rode it around the garage a bit and you might be disappointed to learn I did not skin my knees. But don't worry, I'll have a camera ready for when that happens.

Since everything is thrown together and held with tape and gum, I didn't want to complicate matters too much by adding PID pots. However, it does look like I'm going to have to do just that since plugging the USB cable, changing parameters and then programming is just too slow. 

Right now P=3.5, I=0, D=1. The center/balanced point is not very "stiff", meaning I can easily pull the handle forward until it goes past max angle and stops. I think this is also because "max speed" is too low so there's isn't enough torque to keep balance.

This is where an encoder would work great. With an encoder, I can set max "speed" to 1500, which is max power really. But then I can tell the encoder to only rotate at a certain speed which translates to max torque at all speeds.

Anyway, I'll take a pic tomorrow to show the current messy status.

JR


----------



## phaedrus (Aug 24, 2013)

Good news JR, well done!

It will be interesting to see what numbers you end up with for your PID variables.

Metal folders are very useful, I was using mine again in the weekend (on my build), and have used it many times in the past 25yrs I've had it - certainly a 'must have' in my workshop. Mind you like a lot of these things it could be bigger 

Looking forward to the photographs too... 

P.


----------



## Ovaltineo (Jul 18, 2013)

JR, glad to hear it is sort of working. I think it is OK for you to increase MOTOR_MAX now. I'm surprised you managed to ride it around with the default low values. It was meant to be just enough to balance by itself, not with a rider. I will fix the left right swap in the next release.

Since the default PID values are for a Max output of 255, I'm guessing you can multiply them by 1500/255 for the Roboclaw.


----------



## JRoque (Mar 9, 2010)

Hi all,

Here's some pics and a video of the prototype. The video shakes and turns so much it makes me dizzy, sorry about that.

A couple of things are starting to emerge from my limited testing:

- 24 inches (~600mm) wide is too damn wide! That's the first thing I noticed when I saw a real Segway for the first time at the mall the other day.

- Having a low center of gravity is nice, but I wouldn't be too concerned about it. Mine does but unless I carefully place the batteries and components inside, it still tilts forward.

- For god's sake use aluminum!  Now that I've added 4 SLA batteries this thing weighs a ton, and I still have a bunch of metal parts to add.

Top. If you look carefully, you'll see one of the tires is mounted backwards. That's because these are two front wheels off a Vespa. I'll fix that at some point in the future.










Closer look at the top, showing the DC-DC, gyro and Arduino boards held in place with double-sided tape. Yep.










Front, showing the handle leveling springs. This needs some work and a stop so it can't be tilted too much. But it works well even as-is.










Another look at the electronics. See the gyro mounted at the end of the tube/shaft so that it lives where X and Y intersect with the hope that this minimizes unwanted acceleration.










Now hold your breath, try to keep your lunch down and watch this video showing the scooter as I drag it along by the handle. Towards the end, you can see it rolling down the driveway on its own.





JR


----------



## mizlplix (May 1, 2011)

Grats on the progress! I hope mine works as well.

Miz

(The video is not that bad)


----------



## phaedrus (Aug 24, 2013)

Great progress JR, I'm sure it's a great feeling to see some things moving!

I recall the Segway itself was designed to be no wider than the average person (or something to that effect) but if yours is 600mm wide I don't think that's too bad. 

Mine is slightly more, but I am hampered somewhat by the right-angle motors and the need to deal with them, and allow reasonable ground clearance etc. In order to achieve this I've got the motors themselves in the vertical plane, thus in order to give reasonable platform space for those with larger feet I have keep the width up a bit. With your flat-pack inline motors I guess you've got the possibility to thin it down a little.

I suspect you'll find the SLA's are a fair chunk of your weight, although you did have quite a substantial frame there. I've made my machine semi-unitary insofar as the chassis is concerned which helps I think. I'll measure it later if I can. My main weight increase is the motors and SLA's which seem to me to be reasonably equal. If I were to use Li batteries and alloy (or even plastic!) motors that would change dramatically.

Just for a bit more info I did use aluminium for my steering arm (I suspect yours is quite weighty with that steel pipe and fittings) but not for the monocoque, which would have further assisted in the weight stakes - the main reason simply being that I didn't have any to hand, not because it wouldn't have worked.

Looks like you've used a similar DC converter to me, much better than 78xx regulators these days eh!

Anyway we'll be keen to see further photographs, including of the first crash and full analysis/report on same 

Cheers, P.


----------



## JRoque (Mar 9, 2010)

Hi all.

Thanks P. To those 600mm you'd have to add the width of the wheels so it's wide. When I was designing it I stood on a platform and pictured myself taking a sharp turn. Then again, I should've remembered my mountain skiing and how I keep my feet close together. Oh well, it fits through the garage door 

Yes that's a nice "simple switcher" from National (now TI). I think the RoboClaw motor controller has a built in regulator as well, I need to check on that since it can obviate the extra switcher.

Today I tweaked the parameters a bit more and debugged it using my handy test pilots: my kids. I have two of them in case one breaks down. Along with the kids, I must have ridden it for 2 hours total and it feels a whole lot better. My 6 y/o picked it up in 2 minutes flat, even with the additional instructions she had to hear like "don't step on the wires!".

Remembering that these values apply to my hardware and each hardware combination is different, here's my settings so far:

```
#define KP 3.9
#define KI 0   
#define KD 1.5
#define STEER_MULTIPLIER 25
#define MAX_ANGLE  15
#define MIN_ANGLE  -15
```
The P and D look close to the default values but adjusted for my top "speed". The original steering multiplier was 3.5 but I wanted to turn on a dime (on the spot) with a slight deflection of the steering handle. 

Now, if I only had a 24V charger... Any known good one with proper charging and floating curves?

JR


----------



## phaedrus (Aug 24, 2013)

JRoque said:


> Hi all.
> 
> Thanks P. To those 600mm


Ah, mine's 480mm _sans_ wheels, so I guess yours is fairly wide!




> handy test pilots: my kids. I have two of them in case one breaks down.


Now this I just have to respond to! - wait until the 6yo adds another 7yrs and it will be *permanently* broken for the next 7yrs at least .. That's why I've not got things done today that I was going to (the 14yo waited until 1300 before deigning to get out of bed , grrrr).

I have a 24v charger that came with my scooter that I was going to use but also think it would be good to have something internal to the machine that simply requires mains via an IEC socket. Let us know if you come up with something.

Good news on the rest of it, and thanks for the detail on your PID values. I intend doing a bit more with mine the next day or so (teenager notwithstanding - it's holidays which is why she's home) and will report on the numbers I get, using OT's code.

Cheers, P.


----------



## ketutsapta (Oct 6, 2013)

Dear all,

Introduce my self, my name is Ketut Sapta from Bali-Indonesia. I'm newbie from micro controller user and I'm very very interesting about this project. 

Please help me, I have question, how many part do you use for better performance to build "Segway Clone"? 
1. Arduino Mega
2. MPU6050 or...
3. ...

because I want begin start this project, with Ovaltineo code.
Thank you very much, 
Ketut Sapta


----------



## phaedrus (Aug 24, 2013)

ketutsapta said:


> Dear all,
> 
> Introduce my self, my name is Ketut Sapta from Bali-Indonesia. I'm newbie from micro controller user and I'm very very interesting about this project.
> 
> ...


Welcome Ketut.

I would suggest you have a full read of all the posts on this thread, and on OT's thread - this would give you a good background as to some different ways of building such a machine.

To answer your specific question; in my case I am using the following:

Arduino UNO
MPU6050
Hall-effect sensor (steering)
DC power converter
PWM motor controller (using discrete IRF1405 FET in H-bridge)

None of these things are mandatory - there are many builds using quite different devices (indeed I have used other devices, and other code, on my own machine) - but to achieve a more likely working result from OT's code then using the UNO or MEGA, 2 x MPU6050, and say BTS7960 would be best.

Cheers, P.


----------



## phaedrus (Aug 24, 2013)

*Weights.*

JR _et al_

FYI I weighed the major components of my build today.

I was surprised to find the chassis was as heavy as it was. I guess this is due to the protoyping I did with the framework - in my view an almost completely monocoque construction is possible for the home build, and if one were to use aluminium sheet for that it should result in a much lighter machine. Coupled with LiPo batteries (26v @ ~6Ah for about $80 @ ~1kg) this would make it much easier to pick up and move around...

Here's the list:

Chassis 6.4kg
1 x Motor & wheel 5.5kg (2 used = 11kg)
1 x 7Ah SLA Battery 2.5 kg (2 used = 5kg)
Steering mechanism 0.5kg

Assuming say another 0.6kg for the electronics and misc things then the total machine should weigh around 23kg - quite substantial.

However I see a Segway I2 weighs 47.7kg so I don't feel so bad - albeit the real thing will have a much better range and speed than mine.

There are some things that I may do that would increase the weight (for instance using 2 x 12Ah SLA's that weigh around 4kg ea) but I'd still be a long way from the I2.

A quick calc shows a possible weight of:

Chassis 0.5kg
2 x LiPo's 2kg

Which would knock nearly 9kg off the finished build (with a slightly better battery capacity).

I've not looked into the motor/wheel weights but I'm convinced I've got the heaviest possible motor assy and so am sure that could be improved on also!

Cheers, P.


----------



## Ovaltineo (Jul 18, 2013)

ketutsapta said:


> Dear all,
> 
> Introduce my self, my name is Ketut Sapta from Bali-Indonesia. I'm newbie from micro controller user and I'm very very interesting about this project.
> 
> ...





phaedrus said:


> or MEGA, 2 x MPU6050, and say BTS7960 would be best.
> 
> Cheers, P.


Ketut,
Get what Phaedrus has suggested above. You'll need 2x BTN7960 though. Get a +5v buzzer too. I would suggest getting a prototyping board for Arduino Mega to keep the connections tidy.

Have you got motors and wheels in mind? You need 24v motors with at least 300 watts output. I used electric scooters motors and chain driven wheels which I bought from a local shop. Cheap second hand wheel chair motors seem to be available only in the US.


----------



## ketutsapta (Oct 6, 2013)

Thank you very much phaedrus and Ovaltineo for answer my questions.

I'm sorry my poor English and knowledge about this project, so I have many questions again, I'm send PM to ovaltineo. Thank you.


----------



## PStechPaul (May 1, 2012)

I bought a brake disc and caliper from a company on eBay that also has what I think is a good price on a 600 watt 36V DC motor for $60 including free shipping worldwide (although there may be additional costs).
http://www.ebay.com/itm/271233160726

The store is: http://stores.ebay.com/50caliberracing

They are in Nevada and they are responsive to phone and email.


----------



## JRoque (Mar 9, 2010)

Hello all.



PStechPaul said:


> although there may be additional costs


Hey Paul. I just checked shipping for Australia and it's another $60. But the motor seems nice.

P, thanks for weighing your machine. I still need to find a way of doing that, maybe with two bathroom scales.

So I took another short ride this morning and ended up flying over the handle. Fortunately, I still have the prototype pipe handle without a "T" handlebar at the top so I was able to jump over it and land safely. The reason for the "fall" was that I was leaning too hard forward and the machine ran out of steam to keep me upright. 

I guess I can avoid that by increasing my "max angle" value but at some point, maybe going uphill, I'm likely to hit that max angle again. What is the solution here? Leave a bit of reserve speed from the "max speed" value to push you back when at the brink of going over? Or is this just inevitable and I just need to go slower?

JR


----------



## phaedrus (Aug 24, 2013)

JRoque said:


> P, thanks for weighing your machine. I still need to find a way of doing that, maybe with two bathroom scales.


Yes, that's what I used, but only needed one scale - I just put the machine on them end on which worked reasonably well.



> So I took another short ride this morning and ended up flying over the handle.


Videoed, surely ?



> Fortunately, I still have the prototype pipe handle without a "T" handlebar


This is a quandary that I've not yet resolved. I like the idea of off-setting my bar so that one could effectively just step off the machine, but it may make one feel a little off-balance east-west. Then I thought about not putting the t-bar on (assuming a centre bar), but that doesn't seem quite right either, possibly some flip-up bars might work best.. if that makes sense! Anyway, still to be resolved, presently it's central.



> I guess I can avoid that by increasing my "max angle" value but at some point, maybe going uphill, I'm likely to hit that max angle again. What is the solution here?


As you described the common method is to keep a reserve that's able to kick you back. This has traditionally been 30% - 40% of the absolute max available from the motors. Obviously this slows down the normal running max speed however. 

That's not so bad if you've plenty of speed in hand but certainly in my case that would make it quite slow. I think IIRC your motors are better (170RPM?), whereas mine are 105RPM so you may be able to contemplate this.

Otherwise it's just a matter of not pushing it quite as much - or as OT has suggested include a warning buzzer close to max angle. In my case I will implement a gradual slow-down if I keep a small max angle because I suspect it will be possible to recover, or at least retire more gracefully, from such misdemeanours .



> I bought a brake disc and caliper from a company on eBay that also has what I think is a good price on a 600 watt 36V DC motor


PTP: Thanks for this info, they look good - hopefully KT is reasonably close to the source if he hasn't got anything yet.

Personally I'd like to improve on my 200w motors too but shipping to me is $65USD per unit so it does blunt my enthusiasm a little... it's a common problem for me howerver.

I think if I do end up getting any from away I may try and get something with an integral gearbox like JR's, although at this stage I'm more keen on trying direct drive BLDC, I think there's some mileage in pursuing that, but it's another story really...

Cheers, P.


----------



## JRoque (Mar 9, 2010)

phaedrus said:


> Quote:
> So I took another short ride this morning and ended up flying over the handle.
> Videoed, surely ?


Not to worry, there was no blood or skin loss. I need to record every ride just in case; I wouldn't want to miss that 




phaedrus said:


> I like the idea of off-setting my bar so that one could effectively just step off the machine, but it may make one feel a little off-balance east-west.


Right, I've seen a DIY segway of sorts what uses two handles, much like ski poles. I'm ok having it without the T bar but the wife unit has warn me the kids need one.



phaedrus said:


> As you described the common method is to keep a reserve that's able to kick you back. This has traditionally been 30% - 40% of the absolute max available from the motors. Obviously this slows down the normal running max speed however.


OT, is that something we can add to the code? Since you have to take the machine off balance to make it move the question would be: at what angle do we decide we're falling over versus just riding?

I thought of what P is suggesting, slowing it down past a certain unsafe angle. I understand what he meant but without wheel/shaft feedback, slowing it down would exacerbate the situation as less power would be applied to correct the angle. It's easier for me to picture myself balancing a stick in my hand. If it's falling over, I have to add speed in that direction to keep it upright.

So perhaps we need to decide (if it hasn't been already) at what angles we consider it safe riding and the thresholds that the motors will spin up to bring you back to within those angles. Just to get the ball rolling, I'll say +8 /-4 degrees off center balance is safe, anything beyond that should try to bring you back. 



phaedrus said:


> Personally I'd like to improve on my 200w motors too but shipping to me is $65USD per unit so it does blunt my enthusiasm a little... it's a common problem for me howerver.


For those in AP, it might be cheaper to buy and ship from Taiwan/China. I've seen some very nice BLDC motor/wheels/controllers that, if it weren't for shipping costs to NA, I'd be on it.

JR


----------



## Ovaltineo (Jul 18, 2013)

JR, slowing down past a certain angle will not work on hills or a steep curb. If we say slow down after 8 degrees, then a mere 3 degree tilt on a 6 degree slope will trigger this. Instead, I will add the option of kickback before the motor reaches MOTOR_MAX - this has been proven to work on the real Segway.

But I think maybe your problem is that P is too low. Try to increase P and decrease D. A higher P means you don't have to lean too much to get more speed. Remember, P is multiplied to the angle, while D is multiplied to the speed of change of the angle. So, D doesn't do as much as P if you slowly lean forward.

I also suggest putting in a buzzer. My next release will include a sophisticated patterned alarm module which I borrowed from Multiwii (an open source quadcopter Arduino app). For example, a single really long beep is overspeed while short-short-long beeps will be battery low; short-long-long beeps will be battery very low; and long-long-long beeps will be battery critical.

I wil add a voltage sensor (using a resistor divider) when I update the schematics.


----------



## mizlplix (May 1, 2011)

I am currently studying the encoder part of the Claw manual. I am trying to find how I set it to recognize 360 pulses per revolution. It must be set, or how would it be effective?

Ovaltino: Thanks for all your time and effort in the coding department. It really makes this project easier to comprehend.

I think I will wire up my machine without the encoder support at first, then add them to be able to see how effective they really are and if they are worth all of the added trouble.

Miz


----------



## JRoque (Mar 9, 2010)

Hi.


Ovaltineo said:


> JR, slowing down past a certain angle will not work on hills or a steep curb. If we say slow down after 8 degrees, then a mere 3 degree tilt on a 6 degree slope will trigger this.


Hmmm but the segway will be leveled at any slope so you would still need to push it to 8 degrees forward regardless of terrain slope, no?



Ovaltineo said:


> Instead, I will add the option of kickback before the motor reaches MOTOR_MAX - this has been proven to work on the real Segway.


Great! So there will be a MOTOR_MAX value, which is the absolute motor maximum speed and a "max speed" value which is the maximum speed the motor will normally operate so there's a buffer between normal speed and kickback speed. Or something like that, correct?



Ovaltineo said:


> But I think maybe your problem is that P is too low. Try to increase P and decrease D. A higher P means you don't have to lean too much to get more speed. Remember, P is multiplied to the angle, while D is multiplied to the speed of change of the angle. So, D doesn't do as much as P if you slowly lean forward.


Or, maybe I'm just a big fat guy and the motors have a hard time keeping my fat arse upright  I will try more P and D values but the values I have now were a good compromise between keeping the scooter straight and, when P cranked up, not bucking like a wild horse when it had no rider on - as when I fall off it.



Ovaltineo said:


> I wil add a voltage sensor (using a resistor divider) when I update the schematics.


Excellent. The RoboClaw has voltage and current sensors accessible via the serial port but a divider is easy and generic enough for all interested to make it work.

JR


----------



## mizlplix (May 1, 2011)

> Schematic for UNO and Roboclaw is coming soon.


Cool! Can't wait. Although I think I have it all figured out, it would be good to get a second opinion.

I am building a servicing stand for my full sized machine, where the tires are off the floor. That way it can be brought into my indoor work room where the computer is and will allow me to get it working and adjusted as best as I can before riding it.

BTW: I have decided to designate my 13 YO grandson as official test pilot. He is both faster in reactions and healing than I am. 

I hope to give this whole thing a test saturday afternoon.

(If I have everything hooked up and the code OK. I have as yet to work my way completely through the whole set up routine....calibrate....enable pin....set P values....set motor max value....I hope I do not get lost)

Miz


----------



## Ovaltineo (Jul 18, 2013)

JRoque said:


> Hi.
> 
> Hmmm but the segway will be leveled at any slope so you would still need to push it to 8 degrees forward regardless of terrain slope, no?


Yes, that was a massive brain fart on my side !



> Great! So there will be a MOTOR_MAX value, which is the absolute motor maximum speed and a "max speed" value which is the maximum speed the motor will normally operate so there's a buffer between normal speed and kickback speed. Or something like that, correct?


Yes.



> Or, maybe I'm just a big fat guy and the motors have a hard time keeping my fat arse upright  I will try more P and D values but the values I have now were a good compromise between keeping the scooter straight and, when P cranked up, not bucking like a wild horse when it had no rider on - as when I fall off it.


Sometimes its easier to lose 20kg of weight than fine tune those PD values .
Yes, the PD values really should be different when there is rider on. I wonder if the real Segway has a sensor to detect this or maybe it is using a really clever auto-tune PID algorithm.



> Excellent. The RoboClaw has voltage and current sensors accessible via the serial port but a divider is easy and generic enough for all interested to make it work.
> JR


Hmm, I forgot about the Roboclaw. I think I can add some code for that. No point adding another sensor. Extra sensor will be for non-Roboclaw users.


----------



## phaedrus (Aug 24, 2013)

Ovaltineo said:


> Hmm, I forgot about the Roboclaw. I think I can add some code for that. No point adding another sensor.


Just as a comment, I agree with JR that the voltage divider, feeding an analog pin of the Arduino, is generic, and not specific to the one controller. Thus it could be useful for those using other controllers to keep it this way perhaps?

My build uses a simple LED arrangement for a battery meter - there's nothing special about it at all, indeed there's many examples on the interweb. I'd thought about beeping things but, remniscent of having to look up BIOS codes every time I got an odd sequence from a computer, I decided that it could be a little too cryptic. I think beeping when it becomes critical is a good idea though so I might included that, thanks for the idea.

Cheers, P.


----------



## mizlplix (May 1, 2011)

Sometimes its easier to lose 20kg of weight than fine tune those PD values







.
Yes, the PD values really should be different when there is rider on. I wonder if the real Segway has a sensor to detect this or maybe it is using a really clever auto-tune PID algorithm.


Maybe that is what those foot sensor switches are for, telling if the rider is mounted or dismounted?

Miz


----------



## Ovaltineo (Jul 18, 2013)

I've never seen a real Segway. Does it have a sensor for each foot?


----------



## mizlplix (May 1, 2011)

They have foot pressure pads. Anyways, they know if someone is mounted or empty.

Miz


----------



## JRoque (Mar 9, 2010)

Hi.


mizlplix said:


> They have foot pressure pads. Anyways, they know if someone is mounted or empty.
> 
> Miz


Yep, and boy are those things necessary... I was properly de-shined this morning when the machine ran full tilt going backwards. I need to duplicate the problem to get the exact scenario for when that happens but I did see it 3 times this morning. Strange that I had not seen this before with the same code.

More or less, it happens when there's load on the motors and I tilt it backwards past the MAX_ANGLE parm. The RoboClaw seems to hang to the last command sent. There's a number of possibilities for a root cause but bottom line is that something's happening (or not) in the Arduino. I know this because if I push the reset button on the micro, the motors stop and everything works fine again.

This will likely not be an issue once I install the inhibit relay for the RoboClaw. But I wonder if we can set it so it constantly sends motor=0 speed commands when tilted past max or min angles. I know that happens at least once but perhaps a loop can prevent this issue from happening.

So, just to be clear, I'm not reporting a bug here. If the problem is solved by sending speed=0 commands repeatedly then great but the real permanent solution is to disable the RoboClaw altogether which the code does already.

JR


----------



## phaedrus (Aug 24, 2013)

JR: I wonder if you possibly have a brown-out situation with your power supply to the Arduino?

If your batteries were not well charged (and/or they're older and have a higher internal resistance), or you have thin supply cables, and you have a higher current draw then it's possible I suppose that the supply to the Arduino could drop sufficiently to cause an issue - or even to the controller but I've not idea at all about the schematic of that.

The reason I mention this is that I have similar issue with mine (using a simple PWM controller) where it will lose the plot completely and maintain a heading/speed from where it was last. I don't believe the Arduino is operating properly at that stage so no amount of code to send 0's is going to help IMO. A watchdog might, and I'll have a look at that, but in my case I have been operating mine on 12v as a slow-down measure, and so with a higher current draw it's possible the voltage could drop below sufficient for the DC converter to properly regulate, leading to the aforementioned brownout.

Today I'll up the voltage to 24v and see if the problem persists, and let you know in case it's something worthwhile you pursuing. 

I'm also going to have a play around with some code ideas I've got to sort out one or two other little foibles of my machine 

Cheers, P.


----------



## Ovaltineo (Jul 18, 2013)

JR,

I have seen this under heavy load on my home-built motor controller. It or the Arduino loses the plot and only gets solved with a reset. Phaedrus is right, it maybe a brown out situation. In my case, there were two problems. The serial port is one problem -- a spike can cause a framing error that is only fixed by a reset. Another problem is a spike in the supply to the Arduino can cause it to hang.

That is why I switched from serial to PWM on my home-built controller. I fixed the other problem by isolating the power supply for the Arduino and using optocouplers to send the PWM signals. This worked well until I had another incident when a MOSFET blew. I gave up and bought the BTN7960s which have been working very well even without a separate power supply for the Arduino. It has built-in smarts that is very difficult to replicate with discrete components.

With a serial framing error or an Arduino brown out (hang), sending multiple stop commands will not work. That is why in one of my first posts in this thread, one of the tips I have is to use PWM instead of serial or other digital protocols.

Can you make sure that there is only one ground connected to the Roboclaw? This means that only the battery ground is connected. Don't connect the ground pin in any of the logic inputs. This will ensure that there is no ground loop between the Arduino and the Roboclaw. If you have already done this, then I would have suggested going PWM on the Roboclaw, but as you already discovered, this is buggy and really not an option .


----------



## phaedrus (Aug 24, 2013)

*Bugger.*

Well, we've all heard it and smelt it I'm sure....

... that's right the crinkle sound of frying components, and the hot bakelite smell of burnt PCB 

All because I was messing with some code that managed to do something nasty to the PWM controller input, which knackered several IRF3205's.

Sigh.

OT - I'm going to order some BTS7960 modules, I take it you need two? They're advertised as 'double' motor driver boards but I don't think that means dual motor control (too lazy/grumpy to look it up!).

The next question is to whether to use the BTN or the BTS7960 - I prefer the BTS modules 'cos they come with a heatsink, whereas the BTN's don't. The BTN's however appear to be a better device, albeit marginally (47 vs 43A from what I read). Not a huge difference in cost.

Ah well, on the positive front I went to a swap-meet in the weekend and bought two electric motor scooters with BLDC hub motors that I'm going to investigate. Neither work, and somehow I managed to get the only two in the world with different sized wheels, but they'll serve as a learning platform I expect.

Not quite so cheery, P.


----------



## mizlplix (May 1, 2011)

My original plan was to place an old style car "push to start" switch (a normally off -momentary on) and mount it in the foot platform under the ball area of the left foot.

The ball of the foot is always down and the last part of the foot to be picked up.

That way it knows when it is empty- occupied and most importantly when you just fell off and stop the claw from operating the motors. 

Details to be worked out.

It could give a balance only mode and a full power work mode.

Miz


----------



## Ovaltineo (Jul 18, 2013)

*Re: Bugger.*



phaedrus said:


> The next question is to whether to use the BTN or the BTS7960 - I prefer the BTS modules 'cos they come with a heatsink, whereas the BTN's don't. The BTN's however appear to be a better device, albeit marginally (47 vs 43A from what I read). Not a huge difference in cost.


P., get the BTS7960 with the heatsink like http://www.ebay.com/itm/Double-BTS7...250?pt=LH_DefaultDomain_0&hash=item33848c3522 - some vendors still call it BTS7960 but you will actually get BTN7960 because the BTS7960 is no longer manufactured.

Each BTN7960 chip is only half-bridge, so a module will have two BTN7960 chips. You need two of these modules to drive two motors.


----------



## Ovaltineo (Jul 18, 2013)

mizlplix said:


> My original plan was to place an old style car "push to start" switch (a normally off -momentary on) and mount it in the foot platform under the ball area of the left foot.
> 
> The ball of the foot is always down and the last part of the foot to be picked up.
> 
> ...


Miz, sounds like a good plan. I originally thought of doing it but it wasn't easy mounting a reliable foot operated switch which would not trip if I shifted my feet. An infrared sensor would be better than a mechanical switch. But I haven't had any incident since I used the BTN7960 controllers, so that plan got shelved.


----------



## phaedrus (Aug 24, 2013)

*Re: Bugger.*



Ovaltineo said:


> P., get the BTS7960 with the heatsink like http://www.ebay.com/itm/Double-BTS7...250?pt=LH_DefaultDomain_0&hash=item33848c3522 - some vendors still call it BTS7960 but you will actually get BTN7960 because the BTS7960 is no longer manufactured.
> 
> Each BTN7960 chip is only half-bridge, so a module will have two BTN7960 chips. You need two of these modules to drive two motors.


Thanks OT, I thought as much but was looking for some confirmation from someone who had some!

I've ordered four (my philosophy being always to have spares).. I have also ordered a tube of IRF3205's, having consumed four today (don't ask ). 

Cheers, P.


----------



## phaedrus (Aug 24, 2013)

*Update on the fry-up.*

Well as I stated earlier I usually carry spares for most things and so when I fried the motor controller today, and after rendering the air somewhat blue, I pulled out the spare and installed it.

As you might imagine that went really well and it also promptly tossed some FET's down the tube 

After some extensive fault-finding I have determined it wasn't a software fault, rather it appears to be an inherent issue with the controller board 

For some reason it appears to want to randomly run the motors and then stop them dead within a second of power-on (even when all the pins are low), only when the Arduino is not sending it any PWM. Once it sees some PWM it's fine .

This was ok(ish) when running at 12v but when I upped it to 24v the instantaneous current rush on hard stop/reverse was just too much for the FETs and two shorted, leading to blowouts on the board tracks as well. I think that as I also replaced the relatively thin battery leads with much thicker items there was somewhat less resistance in the path, and so with newly charged batteries the available current was much higher. 

I had thought these were relatively simple controller boards but now I'm not so sure - unfortunately the chips all have their markings sanded away, and there's no revealing detail on the board itself so I'm not able to pursue it too far...

So just to add to the body of knowledge here I have 'fixed' the problem by writing a small bit of code to pull a digital pin high once the Arduino is outputting PWM. This pin powers the controller board - having measured the current consumption at a little over 7ma at 5v this is well within the 40ma available - and so the board is only turned on when a signal is present. 

So far this has worked well, although I'm now loath to apply the full 24v until some replacement transistors arrive, just in case! I had to remove some remaining good transistors from one board to fit to the other and I've not got many more left... 
Of course given that it took most of the day just to get back to square one I've done nothing on some of the coding I was going to do, sigh. 

As I've now got a bit of work on in the next few days it could well slow further work on the machine down a bit, but I'm still going to try and get to do a bit if I can 

Cheers, P.​


----------



## phaedrus (Aug 24, 2013)

*Freeze.*

JR: I wonder if you've discovered any pattern to the lockups you've had?

I did a bit more research into this today - for mine at least I no longer think it's anything to do with power brown-outs; I ran the Arduino and motor controller on seperate supplies and it still crashed (er, both the machine and the software!).

What I did discover, somewhat oddly, is that it generally only freezes when the machine is going in reverse, and most regularly when it is the lefthand wheel in reverse. 

A reset of the Arduino reinstates operation so although I'm no longer happy with the controller following the previous issues described I'm inclined to think the issue is not related to that.

It will be interesting to see if you've been able to establish any reason/common cause to your freezing, and if it's anything like mine.

Miz: How's your build coming on?

Cheers, P.


----------



## mizlplix (May 1, 2011)

Good AM, P:

I have been busy with some honey-doo's and have not worked on the scooter much. I have been keeping up on the threads though.

I have not gotten my small balancing robot platform to work as yet. This is a function of doing other things more than being troubled with it.

I finally have a clear sequence of the steps written down and think I am ready to try again.

But, this is like a blind man trying to navigate a minefield> While I am certainly smart enough to, There was a continuity problem for me.

All you guys are moving on and leaving me in the dust. I do not even understand some of the terms you are using. Well, I do understand them, I just do not know how to do them.

No big, It is just a learning curve issue.

Today, I am going down to Tucson to Ivan's shop and do a motor run on his dyno. I expect it to be a rather full day, but I will get time wednesday to try a run through on the Balancing robot. 

I got to a point where I needed that pesky relay or FET between those two pins on the Claw controller and the Duino board pin.

There was no part number for the FET, so I am blundering around trying to find something that works as a switching relay. So far I tried the two I found in my junk box and failed to get them to work as required.

Well, I will pick it up wednesday.

Miz


----------



## phaedrus (Aug 24, 2013)

Miz: It's good to hear you're busy! 

I can understand the continuity problem, it was some years between the start of my project and where I am now - mostly due to mother nature. It does take a while to come up to speed again.

I'm sorry I can't speak with any experience of the Roboclaw but I had a quick look at the spec sheet just now - what is the FET for? From what I see the Robo requires TTL serial data, which is what the Arduino will be outputting so there should be no need for any level conversion. I imagine JR should be able to confirm that, but you should just be able to connect the two boards directly.

Notwithstanding this, and the dyno run, it will be good to hear how you progress on Wednesday 

Cheers, P.


----------



## phaedrus (Aug 24, 2013)

phaedrus said:


> I'm sorry I can't speak with any experience of the Roboclaw but I had a quick look at the spec sheet just now - what is the FET for?


Ah, I see now having had a look at OT's schematic and code.

From what I understand it's just an enable that effectively powers up the Robo once the code is up and running and the motors are initialised - you could just manually switch it if you wanted. 

I've not read what the Robo will do if it sees no input in packet serial mode but I guess it's even possible a permanent bridge would be fine, although I don't necessarily recommend that! If it were mine I might but then again I've just recently let the smoke out of my controller so I wouldn't trust me 

Just to complete the amusement it's essentially what I've had to do to mine in order to prevent a further smoke-up, albeit there's a bit more to the detail than that... 

Cheers, P.


----------



## mizlplix (May 1, 2011)

The FET is to turn on power to the claw after the duino has booted.

The claw has two pins with a shunting block on them. I remove the block, run two wires to an FET. Trigger the FET with duino pin 7 or8 whatever. 


Which happens after boot.


Preventing a claw caused run away before the duino boots to take command.


Thx to O.T.


Miz


----------



## JRoque (Mar 9, 2010)

Hi.


mizlplix said:


> Preventing a claw caused run away before the duino boots to take command...


And preventing the decimation of anything resembling shins. Ask me how I know.

Ok I did a bit more debugging today to duplicate the hang issue we're experiencing. I can trigger it nearly at will following these steps:

1. Find a ledge, like a step or curb
2. Position your scooter, backside to the ledge
3. Place your foot on the center, top, back of your scooter
4. Apply sufficient pressure with your foot to prevent the wheels from turning (much)
5. Tilt the segway back slowly to make it run in reverse
6. Hang on for a wild horse ride with the scooter pulling backwards and out of the Arduino control

Note that I wore heavy, non-slip gloves and held the handle tight to keep prevent a full runaway. With the machine running wild, I propped it up to get the wheel off the ground. I plugged in the serial port on the Arduino to check the serial debug output.

It is quite possible that the serial debug window needs to be closed and reopen *after* the USB cable has been plugged in. But with the serial monitor window already opened, I did not see anything coming back from the Arduino and it seemed hung. No amount of rocking the scooter back and forth made a difference. I had to push the reset button to have the machine behave again.

I have a DC-DC converter that has a minimum input of 7V and my bus voltage is >24V so it is unlikely that a bus dip is causing the issue. The Atmel chip is set to brownout on anything below ~4.7V (IIRC) and that would cause the chip to reset the program which doesn't seem to be happening here. Something might be crawling back in through the serial port but I believe the issue is happening to P as well and he's not using a serial port controller like the RoboClaw.

If I had to draw a conclusion at this point with the data I have at hand, I'd say the Arduino is crashing after sending a "back" command or setting the PWM rate. I need to try again and see if the Arduino is at all responsive during the wild horse mode.

JR


----------



## phaedrus (Aug 24, 2013)

Thanks for that info JR, very interesting that you seem to experience the problem when it's in reverse as well.

I've pursued this a little further and find that if there is no load on the motors there is generally no problem but if I load the lefthand motor in reverse it will crash the Arduino and nothing short of a reset will restore it. The righthand motor doesn't seem to affect it in the same way. 

I did have the smoke-up I mentioned to the controller board, and had to use FETs from the other, also smoked, board so I supposed there's a vague possibility this could still be an issue (ie. the motor controller) but I'm struggling to see why it should/could crash the Arduino - particularly when I've run it on a separate power supply - but then why does it only seem to happen under load?

Now that I'm much clearer as to how to recreate the problem, and that your problem is so similar, I'm going to spend some time thinking about the possible scenarios. I did look more closely at OT's code around the forward/reverse switching, and also tried some things on the I2C bus but really there didn't seem to be anything much there that should cause it. I also had the 'scope out looking at a few things surrounding power supply and switching pulses etc but again nothing sprung out at me - although it does seem to point to this.

It's most vexing, and I'm inclined to await the delivery of the new motor controllers but with this additional detail of yours I'm now not so certain this will fix it, and in any event it's important to sort your problem out too...

So, time to ponder and see what comes of it!


----------



## Ovaltineo (Jul 18, 2013)

Guys, you must have a reset button, preferably the BIG RED latching emergency stop that you can easily reach. Like I said before, I have experienced this problem, though I can reproduce it both forward and reverse. It is not the positive supply that is the culprit -- it is the ground. A spike from the motor can send the ground into negative or positive (relative to its normal state) -- enough magnitude will hang the CPU.

P, are you using optocouplers between Arduino and the motor controller? I am really surprised that an isolated Arduino can hang like you said. I had the same problem when I first isolated my Arduino. I discovered later that the two switches I am using for the two power supplies had a common chassis ground (I mounted them on an aluminium plate).

I am wondering if the sudden change from full throttle to stop is causing the problem -- this will stop one motor, but it will hang before it stops the other motor. JR, are both of the motors spinning when it hangs?


----------



## phaedrus (Aug 24, 2013)

OT: Good to hear from you.

Just to follow up; I'm not using opto's, although that's an idea, but in my case there's no sudden change that causes it. I can have it lock up even after a gentle move into reverse (or just loading the wheel by hand at slow speed with the wheels off the ground).

Yes I remain perplexed that in isolating the PSU it should still continue to hang the Arduino. I did try looking for ground issues with the 'scope to no avail, although it was a relatively short attempt. I might see if I can follow that up further - it's good that it's now so replicable.

The only thing I'm a little wary of at this stage is that my issue could still remotely be due to a fault in the controller (most likely one of the FETs), and that this could somehow be masking or getting in the way of resolving another common issue that we may all have.

Cheers, P.


----------



## JRoque (Mar 9, 2010)

Hi all.


Ovaltineo said:


> JR, are both of the motors spinning when it hangs?


OT, glad you rebooted without issues.

Yes, both motors spin backwards under that condition. The RoboClaw continues to operate normally using the last sent command. If it had a "heartbeat" function, it would timeout and stop when no command was received.

I do have two ground lines to the motor controller, one for DC bus that goes to the DC-DC and another for logic I/O. I figured the logic grounds were separate since they have one GND line for every I/O pin. In a board with limited pins, that's sort of wasteful if they're all tied to the same ground line.

As with P, I also tilt the scooter back relatively slowly. If I go too fast, the RoboClaw will current-fault, requiring full reset.

Analog Devices makes some nifty chips that have full logic and power isolation using magnetics. There's also spike protectors, zeners, resistors, etc. Using one of those will likely eliminate ground related issues but I'd like to figure out where exactly the issue is coming from.

I'm thinking of adding a WiFi module so I can send more debug info and maybe confirm if the micro does indeed become unresponsive... it might not.

JR


----------



## Ovaltineo (Jul 18, 2013)

P, there is no point isolating the power supply if they share a common ground, even just for logic. You will not see the very fast spike in a scope, unless you have a very fancy sampling scope with gigabytes of capacity. If it locks up under light load, then something is wrong with your controller. It is probably the buffer capacitor, or a defective FET. A FET with a dead zener diode is hard to find .

JR, disconnect the logic ground. This will cause a ground loop. If this doesn't fix your problem, then I suggest separating the power supplies and using optocouplers.

This BTN7960 module doesn't exhibit this lockup problem - http://www.ebay.com/itm/New-Double-...930?pt=LH_DefaultDomain_0&hash=item3f28b7504a. It sounds like I'm the vendor . Maybe the secret is the 74HC244 buffer between the BTN7960 chips and the host. But I think it is the BTN7960 itself and the very, very short tracks in this module that eliminates the spikes.


----------



## mizlplix (May 1, 2011)

i assume the BTN7960 board would replace the Roboclaw?

Would you need two? Or just one?

Miz


----------



## phaedrus (Aug 24, 2013)

Ovaltineo said:


> P, there is no point isolating the power supply if they share a common ground, even just for logic. You will not see the very fast spike in a scope, unless you have a very fancy sampling scope with gigabytes of capacity. If it locks up under light load, then something is wrong with your controller. It is probably the buffer capacitor, or a defective FET. A FET with a dead zener diode is hard to find .


I agree re isolating, the original reason for running the separate supply was 'cos I thought it might have been a brown-out situation and I wanted to rule that out.

I also agree the likely problem is a FET, given the hard time they had! As it happens I have, or have access to, some fairly reasonable gear but by the time I mess with again I may as well just replace the board when the new ones arrive - or replace all the FETs when the new packet of them also arrive  Anyway I do find it interesting that JR's problem and mine appear similar in onset.

There's one more thing I want to try but after that I think I may just wait for the other parts to arrive.

In other news I picked up a couple of electric scooters in the weekend, with BLDC hub motors. I was hoping to use them in another balancing scooter but of course it turned out the wheel size is different  However I decided to get one going (which took some time) and I was quite impressed with how well it went for 300w, I think there's some hope for that project yet...

Cheers, P.


----------



## Ovaltineo (Jul 18, 2013)

mizlplix said:


> i assume the BTN7960 board would replace the Roboclaw?
> 
> Would you need two? Or just one?
> 
> Miz


You need two BTS7960 modules. Each module has two BTN7960 chips.


----------



## JRoque (Mar 9, 2010)

Hello all.

In debugging the hang issue, I rerouted all of my cabling including twisting wires and having a single ground return - I can confirm the "logic" ground on the RoboClaw is nicely tied to "power" ground which is not good.

I tested the wild-horse scenario and could not hang the micro again. Based on this outcome, it is likely that the hang was being caused by a negative spike and could have also occurred going forward but it just so happen that I didn't trigger it when testing. I could only test it 4 times - and one of those cause an over current condition - before the boss called me in for dinner. But so far is a whole lot better than it ever was.

As part of finishing the project, I will add optoisolators to the serial I/O, two cut-off foot switches (in parallel, both must be off before cutting power), a fuse, a RoboClaw inhibitor circuit and maybe a contactor.

BTW, I bought an eBay [email protected] charger that seems to work pretty good. It comes with a male XLR plug. If you need the receptacle, that would be a female XLR chassis mount.

JR

PS: Miz, I have the same gear that you have. Let me know when you're ready to give it a try and I'll hang around the forum to jump in and help where I can.


----------



## mizlplix (May 1, 2011)

Thanks, JR: I am currently switching all gear from the balancing robot model to the full sized scooter...Heh

After I get as far as I can, I will leave a note on the board and we maybe can get together at some time and point.

I am ordering two BTN7960 boards just in case the claw can not be made dependable.

Miz


----------



## Ovaltineo (Jul 18, 2013)

JRoque said:


> Hello all.
> 
> In debugging the hang issue, I rerouted all of my cabling including twisting wires and having a single ground return - I can confirm the "logic" ground on the RoboClaw is nicely tied to "power" ground which is not good.
> 
> ...


Told you so! 

With any luck, you won't need the optoisolatos and a separate power supply. If you can cause an over current without a hang, then its looking good.


----------



## mizlplix (May 1, 2011)

A week ago, I verified that the two small encoders would attach to my motors easily.

So, I started reading up on the Roboclaw's encoder support function. YIKES!

First of all, it was dry reading, plus it looks to be a Chinese translation and other than the statement of "it will support 0-6,000,000 pulses pse second", I can not figure how to set the PPR (Pulses per revolution).

But it looks like it needs the arduino also and is not a stand alone function.

Miz


----------



## Ovaltineo (Jul 18, 2013)

Miz, I suggest looking at encoders later. The Roboclaw has its own PID values when using encoders -- it is very difficult to tune the Segway clone PID and the Roboclaw PID at the same time.

BTW, did you get your machine up and running yet?


----------



## mizlplix (May 1, 2011)

Yes, the encoders will be for MUCH later.

I have everything mounted, wired except for the steering gyro and the FET for enabling power to the Claw. (the wiring is in place for the FET and the gyro, but the FET is still in-the-mail)

I need to weld a small metal tab to the base of the control tiller to mount the board. Then solder the 4 wires to it....Done for that part.

Miz


----------



## mizlplix (May 1, 2011)

I found an interesting thread on the arduino forum about a guy making a balancing scooter with an UNO-Roboclaw and Gyros. He was having strange things happening.

"


> After many detours I finally found a solution to the problem. It came down to some hardware interference that I resolved by:
> 1) moving the RoboClaw motor controller about 10" away from the Arduino board
> 2) installing ferrit cores around both motor cables and the main power cable to the RoboClaw motor controller
> 
> ...


"

http://forum.arduino.cc//index.php?topic=184124.msg1363815#msg1363815


Maybe something to think about, Huh? A noisy Roboclaw?

Miz


----------



## JRoque (Mar 9, 2010)

Hi.

I tried ferrite cores, 2 on the serial port lines but they didn't make a difference. This is likely a low rate (ie: not for ferrites) negative voltage dump on the serial lines. Twisting the cables could help and it is how I did mine. But I also have had the micro away, and 4" above the RoboClaw all along. 

Using a couple of zeners might help protect the micro but, ultimately, optical isolation is the sure bet.

I had a chance to try it some more yesterday. The same ramp that would trigger the lockup before did not have any effect this time. I also tried it with one wheel up on a curb and it worked great. Didn't notice any fading or power loss after about an hour of scooting around. The RoboClaw is using only it's factory heatsink but it didn't seem to heat up much.

Searching YouTube for real Segway falls, they do happen and often. Even with their foot sensors there seems to be a 1 to 2 second delay between the rider falling off and the machine powering down. Those ~2 seconds of delay are when people get run over or scrape the asphalt. I think it would be better if they looked for when both left and right foot switches are off. In that condition, no delay is needed because you're clearly off the machine. An alternative could be the use of Jet Ski type key that you take with you when you fall off. Treadmills have a magnetic key that you pull off when you fall so that could be used as well. 

JR


----------



## mizlplix (May 1, 2011)

JR: 
Do you have some sort of minimal balancing routine when the switches are not closed,(I.E. The machine is just standing there balancing after first turned on)

THEN allows full power after both switches are closed? (Rider mounted)?

Or do the switches just cut power to the CLaw? (That would require you to mount quickly onto a dead machine, then be aboard it while it powers up)



In my imaginings: I would walk up to the machine, turn on the power switch.

The arduino would boot, then turn on power to the claw, the machine would start balancing.....at minimal power.

Rider would then mount, when the second foot would close the second switch, the arduino would then allow full power to be used after the rider is aboard.

Or is this way, way over think?

Miz


----------



## JRoque (Mar 9, 2010)

Hey Miz,

Let me clarify that I have no foot switches at the moment, that's just a future plan.

With the switches attached to the micro, the segway can power up and balance itself normally. OT's code requires it to be within 2 degrees of balanced and that works well. Once you mount the scooter the switches turn into a cutoff circuit. That can turn off power to the controller via contactor or disabling the controller's logic via a lower current relay. It would require a power cycle to return the switches to a functional state. So there are many ways to skin this cat. 

Ironically, my low-center of gravity machine that balances itself even without power are at higher level of safety risk than those that tip over. In it's current prototype configuration with the heavy pipe handle, my scooter tips forward if I'm not on it. Letting it go on its own will cause an oscillation that will eventually tip it over the maximum (actually MIN) angle and make it stop. So the switches are good to force an instant stop but shouldn't be a must have and some applications like mine.

I still don't have a sheet metal bender and I'm afraid to be settling in with the plywood floor. It was quite easy to throw a couple of planks in and bolt them down. The next step is to make a cover for the Arduino, DC-DC and gyro that would mount in the middle of the floor. I'm torn between making a CNC cover out of wood or using two of those to make a mold and press a sheet of aluminum into shape. The first option will be easier but it will only add to the dorky look of the plywood floors.

JR


----------



## mizlplix (May 1, 2011)

Theres one good thing about this type of vehicle.....you can always get it running then have time to make a really nice platform later to transplant the 'tronics' to.

My biggest problem is going to be the slow top speed. About six mph.....

I truly think I will work out the kinks on this one, then maybe later make a chain drive type with bigger and wider tires that goes about 12 mph or so.

Miz


----------



## mizlplix (May 1, 2011)

I think I am through with this thing. I give up.

I had everything hooked up, installed into the Segway machine, steering.....everything....Except for that BS250 FET that powers up the controller.

I have been patiently working for two days to get this thing to work with no success.

I have tried every possible combination of those three wires and ...nothing.

On the Duino I have terminal D7. simple.

On the Claw, I have LB-MB plus and grd. If they are blocked together, the claw boots up on power ON.

I remove the block and installed two push on wires (the type for Duino boards).

So, Now I have a blue wire 1- from D7 (on the duino)
I also have a black wire from LB/MB neg.
I have a red wire from MB/MB Pos.

These FETS have wires 1,2 & 3

Wires 1 and 3 show continuity when off.....
Wires 1 and 2 do not.
Wires 2 and 3 do not.

I have tried ALL combinations of them on the FET including the recommended one. And the FET stays the same.

To add to this I accidentally touched the LB/MB grd to the chassis....Zap!

Now everytime I boot the Claw, I get a red error light. 4 blinks meaning Logic battery over voltage. nothing in the system is over 24 VDC. The claw is supposed to be good for over that.


Swell.

Miz


----------



## phaedrus (Aug 24, 2013)

Never give up Miz, it's all part of the big experiment that this is!

I regret I'm not much help with your controller as I've never seen one but I wonder if you have a circuit diagram for it? It might be possble to ID the likely problem from that perhaps if we could see it - it does sound a little like something's gone awry with it following the short . Alternatively I guess a call to the makers might elicit some info as to what's wrong.

Once you get the controller sorted again with no error we can work through the other problem step by step, starting first by ensuring that the enable pin on the Ruggeduino is doing its thing correctly, then following that through to the FET etc.. I'm sure it will burst into life soon 

Cheers, P.


----------



## mizlplix (May 1, 2011)

I have an email in to the Orionrobotics help/tech office. But I do not expect much from them. They have not been too good in the past for others.

I guess it is time to save up to buy two of the smaller ones....I did like the claw as it was so robust, but it was so complex as to any sort of usage. It was TOO adaptable and confusing to even read the manual. Chinese translations are most times that way.

I grew up with vacuum tubes. Even transistors were high-tech back then. As a consequence, I never went into electronics except for peripherally. 

Miz


----------



## Ovaltineo (Jul 18, 2013)

mizlplix said:


> I have tried ALL combinations of them on the FET including the recommended one. And the FET stays the same.
> 
> To add to this I accidentally touched the LB/MB grd to the chassis....Zap!
> 
> Now everytime I boot the Claw, I get a red error light. 4 blinks meaning Logic battery over voltage. nothing in the system is over 24 VDC. The claw is supposed to be good for over that.


Miz, sorry to hear about your little accident. These things happen even to the best of us. Here's a picture of how the BS250 is supposed to hook up. I don't have a Roboclaw so I don't know which of the LB/MB pins is the source and which is the sink. From your little accident, the "LB/MB grd" is probably the source. We can't use it now coz I think your Roboclaw BEC is fried.

Can you try powering the Roboclaw from the +5V on the Arduino? Do this by removing the LB/MB block and connect +5V from Arduino to LB-IN + pin of the Roboclaw.

If this works, then connect the +5 source of the BS250 to the +5V of the Arduino, and connect the +5 sink (drain) of the BS250 to the LB-IN+ pin of the Roboclaw.


----------



## JRoque (Mar 9, 2010)

Hi.


mizlplix said:


> I have an email in to the Orionrobotics help/tech office. But I do not expect much from them. They have not been too good in the past for others.


Actually, once they take your case and you're talking to Nathan, he will help you immediately. He sent me an updated and upgraded V4 of the board with the USB option thrown in.

Now you have a Roboclaw problem but once you have that fixed, I would recommend you take out as many variables as you can. I have 1 MPU and no Robo inhibitor. After I shake the bugs and/or adjust it to be liking, I'll add a relay/FET, switches, lights, a coffee maker. But any of the extras just cause pain and suffering during the debug stages.

I can't imagine your onboard regulator is toast since it powers the logic still and that regular is a switcher that typically protects themselves from the evils of ground.

Don't give up man. I got into this because of this thread of yours. The captain can't abandon his ship!  Wait until you peel off your knees at least.

JR


----------



## phaedrus (Aug 24, 2013)

JRoque said:


> Wait until you peel off your knees at least.


Well said JR!

I reckon this is the way these things go:

 now why doesn't that work
 I'm sure it should work *poke, prod*
 oh crap! what's that smell?!
 Oh you stupid #$%^&$^$!, why did I do THAT (furtively looking around to see if anyone noticed).

Slight pause for new bits....

 let's just try it this (checking again to see if anyone noticed)
 ooh, it does something (did anyone notice please!)
 let's just casually ride around any see if anyone notices 
 Ow, that hurt, but 

P.


----------



## JRoque (Mar 9, 2010)

Hello all,

So I took the clone around the block today. Total travel was about 1 mile (1.6km). This machine makes everyone sooo happy! My neighbors couldn't help but (point and) laugh when they saw me on the contraption. A car with some kids were just as joyful at they shouted their youth's expressions.. something like "reeeeetard!". Not sure what that means but it made them happy as well.

Kidding aside, this thing is flawless now. No kidding. Absolutely no hiccups at all during the ride. Granted, I had my kids and wife in tow so I wasn't going very fast but it performed great over the rough terrain of driveways and sidewalks. People were generally impressed while at the same time I was embarrassed to be showing a cobbled up pile on junk with wood planks and a lead pipe for a handle. But hey, work in progress. 

Bottom line is that hats off go to OT for an excellent code. With a little tweaking it performs really well. Hope to see others jump in and make their own machines.

JR


----------



## Ovaltineo (Jul 18, 2013)

Thanks JR! I wish I could show off my machine to the neighbors too, but it doesn't have enough torque to go up the steep street that I live in. It crawls up like a snail even if I zigzag. The batteries die after 10 minutes of doing this . 

Except for one state, Segways are illegal in public places in Australia (they are considered unregistered road vehicles) so not many people know what it is. My neighbor even suggested that I should patent my invention .


----------



## mizlplix (May 1, 2011)

When ever I read up on the Roboclaws, they recommend a "hard reset". But do not say what that is. or how to do it.

Is that like a cold boot as opposed to a warm boot? 

When I get tired of waiting, I can call the tech number I guess.

To my knowledge, my pack is not grounded to the chassis. (Unless it gets done inside the motors) The wheelchair was ground isolated because of the environments and oxygen use. I thought I was too.

Anyways, still waiting on customer support and the company forum help section.

Miz


----------



## JRoque (Mar 9, 2010)

Hi Miz,

I would write back asking him to be more specific and pointing out the manual doesn't say anything about "hard reset".

OT: I wish it weren't so expensive to ship to AU. I have a pair of monster wheelchair motors (like Miz has) that would be perfect for that hill. 

Hopefully the Segway laws don't apply to your scooter. Yours is an experimental, low-speed vehicle and more like a motorized toy for kids. They also banned Segways on sidewalks in most places over here. Electric bicycles are also banned on public roadways since they are "motorized vehicles".

JR


----------



## mizlplix (May 1, 2011)

In that respect, we here in Arizona, are lucky. 

1- ANYTHING under 49 CC is not required to be registered or plated. The DMV said that Ivan's electric bike was not required to be titled-registered-plated or insured. 

They also had a 2HP maximum too. Most just take the I.D. tags off of the motor.

We do not have any Inspections to go through either. 

We do not have any special certifications for the equipment.........

For instance: I bought an ICE kit for my grandson's bicycle. Two were offered: 48 CC and 80 CC. One was legal for no plates and one required DMV certification after completion.

I (of coarse) bought the 80CC kit. It came with NO numbers or ID on the motor. I engraved a "Chinese name" and "48.5 CC" on it. Instantly legal.

BUT, If a local cop catches you doing 30 MPH on it, you will get a ticket as a 48 CC bike should not be able to go that fast. 

Then you really get hammered good-or would that be hammered bad? (I guess getting hammered good is also bad......) 

I need more coffee. excuse me.

Miz


----------



## mizlplix (May 1, 2011)

UPDATE
____________________________________________________________

At first, I contacted micro robotics, whom was my vendor for the controller.
After two emails, they admitted they could not help.

Then after a post on a Robotics forum under the Roboclaw section, the chief tech gave up and recommended I call Orion.

I emailed Orion Robotics and got a response a few days later. They said I had it hooked up wrong and to read the manual.......

I patiently replied that I had a good overall knowledge of their controller and it was hooked up correctly.

They replied I needed to do a test. I performed the test and posted the results.

They passed me off to another tech, who had another test, which I performed.

He passed me back to the first tech and told me to "call" him yesterday, I did and got a "there is no one to take your call" recording. I left my contact information for the guy, who emailed me to re-try "tomorrow" which is today.

I plan to call "Nathan" several times starting at 11 AM Arizona time, until I get through.

I need to determine what my next step is to be. If I have wasted $125 USD and need to buy a new controller, I need to know and get started ASAP.

I will not get another Roboclaw, but two of the other controller boards listed in the code.

So far I have determined that the board "sees" the 24 VDC pack input as "too high" and the 6 VDC Logic power input as "too low" although I have tried 8 VDC also and got the too low message too.

The logic voltage regulation circuit is working because the error code changes from "too high" to "too low" when I apply power to the LB/MB pins.

The regulator seems to not pass through or recognise a high enough current or voltage.

More later,

Miz


----------



## JRoque (Mar 9, 2010)

Hey Miz, well that sucks. Did they tell you how to "hard reset" the board at all?

The high and low voltage limits are something you can set within the firmware but I'm not sure if you can do that whilst in an over-voltage error condition.

I know you're trying with the RoboClaw but see if you can stick with it a little longer to get it fixed. Mine's working great with no need of additional heatsinking which I found surprising for such high power device. It's also a $125 investment that would be a shame to lose. I'm sure Nathan will help you once you reach through to him.

JR


----------



## piotrsko (Dec 9, 2007)

miz: Can you swap the leads on the logic inputs? -6v would definitely be "too Low"


----------



## mizlplix (May 1, 2011)

Hi guys:

I finally got to talk to Nathan. He just said to examine the connections on the board for cold solder joints....I said "Wha?"

They are too small to even see, even wearing my best magnifyers...LOL

So, I sent it in to them friday about 3:00PM. 

Now I'm waiting on the verdict.

BTW: Way back in the 1980's, My wife was a technician at Hughes on the "Longbow" models. She said it was a really nice bird with field replaceable electronic modules . The crew chiefs then sent the defective module back to Hughes for repairs.....

Repairs: Throw into a pit and burn. Sell scrap to salvage operators. Snag a new one off of the production line.

We now have technology that is too complex to even troubleshoot and repair. Plus it is cheaper to just throw it away. The production line makes the things as cheaply as can me made.

I expect Orion to follow suit and just send another board back.

No, reset means to boot. No magic there.

Dean


----------



## JRoque (Mar 9, 2010)

mizlplix said:


> No, reset means to boot. No magic there


Oh for god's sake, really? Couldn't they just say that?

A bit off topic but yes, repairs are getting to be more difficult these days. The problem I'm seeing is that most stuff made in China (ie: all) is made with parts available only to them. They are either Asia-only parts with no distributor elsewhere or parts made exclusively for high production levels that cannot be purchased in smaller quantities. I have come across more and more of these seemingly simplistic devices that can't be repaired. 

On the Orion board, in particular, they've gone the extra step to scratch off the markings from their chips so there's no reference as to what they are. They do this primarily to fend off bootleggers ready to rip off the design and copy/paste over in China - no research and development, design or testing investment, just like they like it.

JR


----------



## mizlplix (May 1, 2011)

My controller is at the MFG. ATM.

I will add more after I find out what is up.

Miz


----------



## Ovaltineo (Jul 18, 2013)

JR,

Can you please confirm which pin is the BEC source, is it MB/LB+ or MB/LB-? I will update the schematic if it turns out to be MB/LB-.


----------



## mizlplix (May 1, 2011)

On the Roboclaw controllers, 

The first two pins are for the logic battery. (LB)
The one nearest the board edge is the positive, the other is negative.

The second two pins are the Main or Logic power source selectors and need a block tying them together to power from the traction pack.

To use external power, leave the block off of the second two pins and run 6+ VDC or better to the LB+ pin and a external ground to the other LB pin.

They need 6+ VDC or better to power the Claw. (or the regulator will reject the power source) Shoot for 9-12 range. The claw regulator will only allow the correct voltage to the claw logic circuit.


NOTE: In packet serial, the S3 terminals can be wired up to be a claw kill switch. (Disable)

Miz


----------



## Ovaltineo (Jul 18, 2013)

Miz,

Yes, I can see those in the technical document. But I still don't know which pin is the +5V internal BEC source. This will confirm if the MOSFET schematic is correct.


----------



## mizlplix (May 1, 2011)

The second row is the LB / MB selector (Marked by the screw)
The block goes there when operating from internal power.

The first pin/first row is for logic power + (LB IN= logic board power input)
All pins near the edge are positive as indicated.









Leave off the block when using an external power source.
The external source must be +6vdc or greater.(or the input regulator will ignore it)

The enable MOSFET can simply take the place of the block if internal power is used. Otherwise the MOSFET can provide power to the first pin/first row.

Miz


----------



## Ovaltineo (Jul 18, 2013)

Yes, but which of those two pins goes to the MOSFET source and which pin goes to the MOSFET drain? Unlike a relay, they cannot be swapped.


----------



## alvinlkk (Nov 14, 2013)

Hi, is this tread still alive?

Im Alvin from Borneo, Malaysia. im interested to start this project.

anyone here to guide me which is the easiest way to do with the electronics?
any websites or forum?

i will be really appreciate if anyone could help. thanks in advance


----------



## mizlplix (May 1, 2011)

Hello Alvin:

Yes, It is still alive. I am just waiting for a replacement Uno board.

There is another thread here: 
http://www.diyelectriccar.com/forums/showthread.php/ovaltines-segway-clone-89471.html

It deals with the software coding, wiring and components needed.
The README file has all of the needed details and procedure to install,
hook up, calibrate and debug.

We are all using slightly different combination of components, but the best seems to be these:

1- An Arduino UNO or Mega board. Use a real Arduino board, not a clone. That makes drivers and the coding easier to work with.

2-We are using three types of motor controllers: aRoboclaw, Sabertooth or two BTS7960 boards.

3-We also are using two seperate gyro/accel boards-MPU6050-
one for the tilt and one on the tiller stick for turning.

4- 24 VDC battery packs.

Ovaltino has contributed a large amount of time and labor to writing good Arduino code and making it work with several different combinations of hardware too.

Here is the link to download Ovaltino's code: 
http://www.diyelectriccar.com/forums/attachment.php?attachmentid=17419&d=1384375746

The wiring diagrams are in the first post also.


There is really four or six people that are here on these two threads adding knowledge.

Welcome to the forums and to the thread.

Miz


----------



## Ovaltineo (Jul 18, 2013)

Hi Alvin,
Did you mean basic electronics or the details of a Segway clone schematic? This is an easy project for someone with basic electronic skills, eg knows how to read a simple schematic. If you don't know the difference between a resistor and a capacitor, then I would suggest you get a friend to help you. This project is quite dangerous to people who know what they are doing, and a lot more to those who don't.


----------



## alvinlkk (Nov 14, 2013)

Hi Miz and Ovatino. thanks for the quick responds.. i'll gather my parts first. thanks


----------



## alvinlkk (Nov 14, 2013)

hi Ovaltineo. thanks for the advice. i can see this is quite easy project.
but im totally blank on the coding... but will get a friend who more understand


----------



## alvinlkk (Nov 14, 2013)

just wanna make sure, i saw this ad in ebay

http://www.ebay.com.my/itm/Invacare-111708-Electric-Motor-for-P9000-XDT-Wheelchair-DC-24v-3-6a-120rpm-/360732693400?pt=LH_DefaultDomain_0&hash=item53fd581398&_uhb=1

an Invacare motor. are they good for my DIY segway project?

out of 3 schematics from Ovaltineo i chose the 1st one. 
with the -
2 x BTN7960
2 x MPU6050
1 X Arduino Mega or Uno? which one is easier


----------



## JRoque (Mar 9, 2010)

Hi!


alvinlkk said:


> ..an Invacare motor. are they good for my DIY segway project?


That motor is good but you'll need two of them. I can vouch for these guys on eBay: http://www.ebay.com/usr/mobility-equipment-thrift-store

Are you in Malaysia? If so, shipping from USA will be nearly as much as the motors themselves as they are very heavy. See if you can source locally.



alvinlkk said:


> 1 X Arduino Mega or Uno? which one is easier


That one's for OT but I'll just say that it makes no difference since his code runs on both. The UNO is sufficient for this application though having more resources with the Mega is always a good thing.

JR


----------



## robertholmberg (Oct 26, 2013)

Hi,

I am thinking about how you guys did with a fuse, did you use it, and if, where do you have it? What size are you having on what motor? Because im thinking it could be dangerous if it dies in the middle of a run, but maybe better than the equipment to burn. So I wonder how you did it.

/Robert


----------



## mizlplix (May 1, 2011)

R:

I used the original 70 Amp circuit breaker from the wheelchair.

It is mounted right after the battery pack + before it goes to the main pack switch.

The motors are 30 amp each. (for 60 amp plus a little head room)

No other protections are used as all of the wire runs are extremely short,
supported and internal.

Miz


----------



## thanhduy_meo (Nov 16, 2013)

Hi all, I'm very excited in Segway, and i want to make ones, i have a problem about sensor, infact i haven't good at C, comunicate Atmega 32 and Mpu 6050, i use AVRcodevision. Someone help me about this, if you had done, 
Good Health for all.
Thanks all.


----------



## mizlplix (May 1, 2011)

Than: To better understand the sensors and coding read this thread:
http://www.diyelectriccar.com/forums/showthread.php/ovaltines-segway-clone-89471.html

I do not do coding. Everyone here uses Ovaltino's code expertise.

Miz


----------



## Ovaltineo (Jul 18, 2013)

alvinlkk said:


> out of 3 schematics from Ovaltineo i chose the 1st one.
> with the -
> 2 x BTN7960
> 2 x MPU6050
> 1 X Arduino Mega or Uno? which one is easier


I would go for the Mega. It has more memory and I/O ports including multiple hardware serial ports. A Mega clone will cost you less than $17 in ebay - search for Funduino.


----------



## Ovaltineo (Jul 18, 2013)

thanhduy_meo said:


> Hi all, I'm very excited in Segway, and i want to make ones, i have a problem about sensor, infact i haven't good at C, comunicate Atmega 32 and Mpu 6050, i use AVRcodevision. Someone help me about this, if you had done,
> Good Health for all.
> Thanks all.


Sorry, I can't support another platform. You are better off getting a $17 Arduino Mega clone and use my existing code.


----------



## robertholmberg (Oct 26, 2013)

Wow, 70 amp seems like a big one. Cant find any big resettable ones like that. But I find some smaller 30A and thinking of putting them just before each of the motors, would that work just as good?

Haven't calculate that much, but if i will use a 36V (1000W) motor running 24V I guess i will have ~30A on each of them. and then it would work, wouldn't it?

/Rob


----------



## mizlplix (May 1, 2011)

Fuses and breakers are for protecting things. If you put them next to the motors, they do not protect much but the motors themselves.

You need a main switch and fuse/breaker just off of the battery pack that would protect from accidental wiring grounding and fires or melting.

You can find bigger ones at NAPA or an auto supply that deals with big, add on stereos.

Extras at the motor would protect the motor from being overworked if sized right though.

Miz


----------



## alvinlkk (Nov 14, 2013)

found this BTS7960B saying "Double BTS7960 large current (43 A) H bridge drive" 

not sure whether i can use this or not cause easily to buy from ebay

http://www.ebay.com.my/itm/Double-BTS7960B-43A-Motor-Driver-High-power-module-smart-car-driver-For-Arduino-/290925938697?pt=LH_DefaultDomain_0&hash=item43bc898809&_uhb=1


----------



## robertholmberg (Oct 26, 2013)

Alvinlkk, 

Thats the one many here is using. Remember that you will need one for each motor though.

/Rob


----------



## mizlplix (May 1, 2011)

And a small fan over them is recommended.

Whereas a fan on the roboclaw is not needed. (But I have one anyways).

Miz


----------



## alvinlkk (Nov 14, 2013)

im gathering my parts now.. thankss to everyone's help here. following tight with this forum now.

- do i need a buzzer? 
- im thinking to get a 4x4 side steps to make my stepping frame since its aluminium. any opinion? 
- i can easily get 12V 7.0Ah batt here. its writen lead-acid type rechargeable batt. are they ok to use?
- im gonna have many more questions to ask here in the future... thanks in advance

Al


----------



## mizlplix (May 1, 2011)

Yes, you will need a buzzer. like this one:
http://www.ebay.com/itm/320717913686?ssPageName=STRK:MEWNX:IT&_trksid=p3984.m1439.l2649

12VDC X 7.5 AH SLA batteries is what I used also.








I paired up two in series (three pairs), then wired them in parallel
for my 24VDC pack voltage.

They are charged through the wheelchair charge port and I am still using the wheelchair charger. 

I do not like those push-on fittings for high current, so I soldered them to the battery terminals and again at the extreme + and - ends, where I used a small Anderson connector. (Also off of the wheelchair) So the pack can unplug and lift out in one piece.









Miz


----------



## alvinlkk (Nov 14, 2013)

Hi everyone... Good morning from Borneo

this is what i found for the DC-DC stepdown. i've seen this post again and again. found out that this is the one everyone using here right? hopefully im not wrong cause i've already bought this item.

http://www.ebay.com.my/itm/LM2596-DC-DC-StepDown-Adjustable-Power-Supply-Module-/330702825496?pt=UK_BOI_Electrical_Components_Supplies_ET&hash=item4cff6ca818&_uhb=1


----------



## robertholmberg (Oct 26, 2013)

Yes, it will work very good. - Unless its broken


----------



## mizlplix (May 1, 2011)

Not everyone uses an expensive solution.

I am using a simple IC chip voltage regulator to turn my 24vdc pack voltage down to 12vdc to fed the arduino.

Cost was about $0.95

Miz


----------



## battagae (Aug 13, 2013)

What should I be looking up to find those bearings I can mount to the frame for my steering shaft? I have a 1" diameter pipe and I can't find them anywhere. Would they have them at a hardware store?


----------



## mizlplix (May 1, 2011)

Inch sized bearings are rare these days, as everything is metric now. 

Your pipe is a little big I feel.


Home depot has 3/4" cooler bearings. They also have 3/4" solid shaft in the metals bin.


My tiller is a 48" tube extension for a ceiling fan. Also from home depot.
It slides ove the solid bar and needs one 1/4" hole with threads in the bar to mountbthe tube. You will need to bend the 3/4" bar about 80 degrees, which requires an acetylene/oxygen torch to get it hot enough, or a charcoal forge and lots of time.


A small bicycle goose neck fits inside and uses the original bike bolt and wedge to mount.


The handlebars are 3/4" mountain bike, or anything 3/4" O.D.


I would rather use solid pillow block bearings which can be ordered at a tractor supply or even NAPA. If you do not have a good bearing house nearby.


Miz


----------



## mizlplix (May 1, 2011)

I just got my replacement UNO in the mail. I will be remounting it and doing the basic hook ups without any extras, just to keep everything simple.

After I have the vehicle operating, then I can start adding the separate added features, like kill switch, controller boot up delay and such.

More, soon.

Miz


----------



## alvinlkk (Nov 14, 2013)

great.. i cant wait to see the result..


----------



## jaroo (Nov 15, 2013)

Hello folks! 

Thank you for this awesome thread. I am from Slovakia and would like to build my own clone of SEGWAY. I have two bldc engines and a controller and I am seeking for advice how to link arduino and controller, which is having control voltage of -10V to +10V. I have also attached scheme for reference. Appreciate any help. 

Thanks so much


----------



## phaedrus (Aug 24, 2013)

jaroo said:


> I have two bldc engines and a controller and I am seeking for advice how to link arduino and controller, which is having control voltage of -10V to +10V. I have also attached scheme for reference. Appreciate any help.


Welcome.

It would be unusual for a modern motor controller to only have an analogue control input I would have thought - do you have a make/model for it? Even better would be a link, from that we might be able to see if it's possible to feed it a PWM signal or some other data format to control the motors.

FYI I have previously declared an interest in using BLDC motors for this project so will be interested in seeing how this works for you.

Cheers, P.


----------



## mizlplix (May 1, 2011)

Today, I am officially back from the holiday, as I just got rid of the last relative last night. (I only work on any projects while I am alone with no distractions.)

While I was assured that this replacement "UNO" was actually an Arduino brand, after receiving it, It was not. Only "Compatible".

Well, I can get it to communicate with my Android tablet just fine, but I can not find a serial port monitor in the client for Android.....Hmmmmm?

I am still looking. I HAVE been known to screw up occasionally. LOL

It uses a "Micro" USB port for communication. 

I CAN get a Mega though. The local hobby shop has one.....an option.

Miz


----------



## phaedrus (Aug 24, 2013)

Good to hear you'll have a bit more time for the project Miz.

I've never used an Arduino connected up to an Android device but there are various terminal apps that would probably read the data ok - F-Droid has one on it IIRC.

Interesting your 'Uno' has a micro-USB connector, all mine are the standard size, not that it should make any difference to its operation.

Hopefully you'll sort it out and we'll see a new progress report from you shortly!

Cheers, P.


----------



## jaroo (Nov 15, 2013)

phaedrus said:


> Welcome.
> 
> It would be unusual for a modern motor controller to only have an analogue control input I would have thought - do you have a make/model for it? Even better would be a link, from that we might be able to see if it's possible to feed it a PWM signal or some other data format to control the motors.
> 
> ...


Hello. Thanks for your response. I got these engines from the old CNC machine, so I would not say they use new technology.  The type of engine is Dukermotoren BG83x90 and controller BGE4010A.
Here is some documentation that I have found on the internet:
http://www.rwkorea.co.kr/ex/dunkermotoren/BG_E.pdf
http://www.microprivod.ru/files/IM/dunker/IM_BGE4010A.pdf


----------



## mizlplix (May 1, 2011)

When I originally bought the wheelchair, I planned to use the controller out of it in the project.....I was somewhat naive in my planning.

The original controller was not able to communicate with the Arduino board. It was built to accept inputs from a joystick only. Possibly I could have worked out a way around it, but I am not that smart in this area.

So, I went with a Roboclaw 40 amp controller, which has three ways to communicate. Packet serial being the one I used.

Miz


----------



## mizlplix (May 1, 2011)

Success! 
______________________________________________
I finally found an "Arduino" brand Uno and have it mounted in the chassis and ready for hook-up.

Meaningful progress is at hand.

Miz


----------



## Ovaltineo (Jul 18, 2013)

Miz,

A lot of suspense hanging in the air !

Refer to my latest schematic for the Roboclaw - I have removed the enable output from the Arduino. It didn't work out for you last time. Instead, I recommend just using an emergency stop that connects S3 to ground. Note that once engaged, releasing emergency stop will not resume operation of the motors unless the Roboclaw power is recycled.


----------



## robertholmberg (Oct 26, 2013)

Miz, a congratulation. Do we see a video of you driving it?

OT, the drawing you updated last got some connections to much, the buzzer is connected to all arduino pins on its way to pin 12. On the picture for mega, 7960 and mpu6050.

/Rob


----------



## Ovaltineo (Jul 18, 2013)

robertholmberg said:


> OT, the drawing you updated last got some connections to much, the buzzer is connected to all arduino pins on its way to pin 12. On the picture for mega, 7960 and mpu6050.
> 
> /Rob


Thanks Rob. Fixed it.


----------



## RickSoares (Mar 4, 2014)

Hi Ovaltineo... h r u???

I wonder if that Segway Clone project vc developed with Arduino Mega, mpu6050 and btn, is working if there was a change in the design ... My dream is to build one, and I follow this "tutorial" to make my in reality is a technical school project, I am doing a course completion project, called alphaway, and I am willing to follow your path, for the btn it is easier to find in Brazil ...
What would you advise me?
I can hook up your system ??? I'm ready to buy the necessary equipment ...

help me in answers ?? thanks!
I already destei your program, and I had no problem at all in check and compile it ....
already it worked first.

tks...


----------



## Ovaltineo (Jul 18, 2013)

Hi Rick, for a start, you posted in the wrong thread -- this is pretty old. Look for "Ovaltine's Segway Clone" thread which is more up to date. The BTN is supported and is a cheap controller. It works well on flat terrain but could blow or (much worse) short-circuit under heavy load (steep incline). I suggest using short gearing to get more torque at the expense of a lower top speed.


----------



## RickSoares (Mar 4, 2014)

thanks for the reply, I already found another topic, any h bridge serves the project, without changes in programming?
I already developed an H bridge for 100A each side ... believe it would be enough, but do not know what to do with programming, and the drivers of sabertooth, has in Brazil and to bring out of the country is almost 4x his value ...


----------



## Speaner (Oct 21, 2015)

mizlplix said:


> Hello Alvin:
> 
> Yes, It is still alive. I am just waiting for a replacement Uno board.
> 
> ...


Good morning *Mizlplix*.
Very good and interesting this topic on your project , Lily it completely but to try to check the above link which mentions the final code Ovaltino's listed as invalid, can make it available again?
Another question I am designing a Segway but using two shields BTS7960 with a single MPU6050 GY-521 model, you can use your code or do I have to be using 2 MPU6050? 
Big hug.


----------



## roscoopc (Oct 14, 2014)

You can find the latest firmware version at https://github.com/ovaltineo/SegwayClone


----------



## alexander_456 (Oct 27, 2015)

It is an awesome job! I browse your forum and you guys do real wonders. 

I wish I could do something similar, but I'm just learning..


----------

