PDA

View Full Version : PBP projects for R/C models



Pages : 1 2 [3] 4

ScaleRobotics
- 17th October 2010, 03:47
Thanks, you reminded me. To get it in HID Bootloader mode, you have to press one of the buttons while you plug the USB cable in (the program button I think). Once it is powered, I think you can let go of the button. Then see if HID Bootloader recognizes it.

The FTDI is for versions prior to 1.80 (once you get the Hex file into it). But since we are trying to use 1.80:
"CPUStick.inf (http://cpustick.com/cpustick.inf) file needed for Windows (v1.80) -- just save to a file, right-click, and select Install, and you're ready to go!"

Kenjones1935
- 17th October 2010, 15:00
Push down PROGRAM button while inserting USB cable and==>


HID Bootloader says, "Device attached"
red, blue and yellow LED's illuminate.
white and green LED's alternately flash.

We have PROGRESS on a beautiful Sunday fall morning (the colors are peaking this weekend. there is snow on the tops of the Vermont hills) in sunny scenic Fitchburg, Massachusetts.

Ken

Kenjones1935
- 17th October 2010, 15:55
Below: my PC listed CDC RS232 Emulation Demo before. Now it does not.

scalerobotics,
I pulled out the new PICWhacker and plugged in the USB connector. My PC immediately sang its song and gave me the NEW HARDWARE DETECTED GUI.

Under Other Devices it says "CDC RS232 Emulation Demo". Then it asks for a driver. I have installed the .inf file. What is my next step? Also please note that the USB port powers the blue LED on this Whacker. On the first board only the PICkit2 powered that LED.
Ken

LED's flash. HID Bootloader seems to work. Hyperterminal does not work. A GUI told me to restart the PC. That changed nothing. What happened to the "new device"?

Ken

Kenjones1935
- 17th October 2010, 16:12
Pushed the RESET button on the BITWhacker. This produced a different pattern of illuminated LEDs. Yellow one flashing. Blue one steadily ON. The PC claimed it saw a new device. I found the StickOS file and called the new port C4.

My hyperterminal added C4 to my choices. I typed the Enter Key. LO and BEHOLD text!!

Now what - I am not sure. I need to give serious thought to my teach the teacher Professional Development seminar.

Walter Scalerobotic Thank you!!

Ken

ScaleRobotics
- 17th October 2010, 17:06
Now you can start to write some simple programs. They show some examples in the manual. You will need to look through the Quick Reference guide here: http://www.cpustick.com/downloads/quickref.v1.80.pdf for all the commands.

Some of the interesting ones are:
help
help pins

And you can set the heartbeat LED (if it is not blinking already) by:
pins heartbeat RA1
(You will have to look on the board to see which port goes to the LED you want to set as heartbeat, RA1 is PORTA.1 and works on my Explorer 16 board).

This prints out an analog result to the terminal:

10 dim pot as pin an5 for analog input
20 print "potentiometer= ",pot

You would probably be interested in the Servo example on page 30:


> new
> servo
45
> 10 dim servo as pin dtin1 for servo output
> 20 for servo = 50 to 250 step 10
> 30 sleep 50 ms
> 40 next
> run


Note that you will have to change the servo out pin to one your hardware has. To see the available ones, use the "help pins" command. It will show you at the bottom which pins are available for the servo command. In my case, I changed dtin1 to rd1.

Kenjones1935
- 17th October 2010, 22:57
scalerobotics,

My focus is changing from teaching STEM to middle school kids to teaching the teachers about teaching STEM to public school kids.

Documenting our conversations over the last months might give me some insight on the process. Is there a way to capture this thread as a .doc or a .pdf file?

Ken

ScaleRobotics
- 18th October 2010, 00:50
Documenting our conversations over the last months might give me some insight on the process. Is there a way to capture this thread as a .doc or a .pdf file?

Once a routine is made, a lot of it can be forgotten (thankfully). I don't see any good ways to do this, but here is one way. It will only get you 40 posts at a time though. I have looked for a way to change this setting, and it looks like it is not settable, at least by me.

If you goto thread tools, and click on show printable version, you get something of a better format. Then you can go to file, and save as, and save it as html. While you are on this printable version, you can then select the next page of posts, and select save as, then call it page2 or something. This isn't ideal, but it's the best I can come up with.

Kenjones1935
- 18th October 2010, 01:02
The cost of the PICWhacker ~$40 is too much. Its appeal is that all the PICspins are available through 0.1" centered holes. Is there any PC product of which you know that has this PDIP configuration with only the PIC and a USB connector aboard? You guys had a forum "off topic" that sounded like you all built some yourselves. Did this work? I know that I could not solder those tiny leads on the PICWhacker board.

Ken

rmteo
- 18th October 2010, 02:45
You have the $2 option by going with a 40DIP PIC16F887/4 and mikroC.

Kenjones1935
- 18th October 2010, 02:58
My big hesitation with switching to MicroC is configuring a USB connection. I have been very successful with the PICkit2 package.
This experience with the USB port using Hyperterminal has taxed my understanding of the system.
I hesitate to change. I assume I can get a USB compatible (0.1" centers) connector at our local YouDoIt Electronics store. I'll do more reading from the mikroBasic WEB page.

Thanks, Ken

Kenjones1935
- 18th October 2010, 03:23
I just now found that very tiny Power Source switch. On the first board is was in the wrong position to get power off the USB.

Now it tells me!

rmteo
- 18th October 2010, 03:45
My big hesitation with switching to MicroC is configuring a USB connection.

Why would you need a USB connection? Just program the PIC with the PicKit2 (or other compatible programmer) using ICSP - mikroC or mikroBASIC doesn't care.

mackrackit
- 18th October 2010, 06:08
http://mackrackit.cambs.net/Kenjones1935/

Kenjones1935
- 18th October 2010, 14:29
Trial and error tells me that the only way to reconnect hyperterminal via C4 (the USB) to my BITWhacker after physically dislocating the connector is to be holding down the RESET switch while inserting the USB connector.

Anybody see that written down anywhere?

Thank you both for the leads to documentation of this thread.

Ken

ScaleRobotics
- 18th October 2010, 16:53
Trial and error tells me that the only way to reconnect hyperterminal via C4 (the USB) to my BITWhacker after physically dislocating the connector is to be holding down the RESET switch while inserting the USB connector.

Anybody see that written down anywhere?

It is sort of documented.....

I think this is an effect of having the bootloader resident on the device. You "should" be able to either have the bootloader resident, with StickOS in the program memory (sort of underneath it). Or, to get rid of the "feature" you found, program over the whole thing, using your Pickit2 with the StickOS with the shorter name (not meant for bootloaders). Though I am a little hesitant to have you do that to the working device. Better off trying this on the non-working one, and see if we can revive it.

I think, then you would have it immediately recognized when you plug it in to a port, without pressing a button.

When I say sort of documented, it is at the bottom of the UBW32 page here: http://www.schmalzhaus.com/UBW32/doc/UBW32BootloaderDocumentation.html Does this explain what you have found?

In my search, I also found a page that has the pinouts for the device in a readable format. http://www.schmalzhaus.com/UBW32/doc/BoardReleaseNotes.html

As for your question about the other off topic thread: We had a member graciously volunteer to build some StickOS devices. But it is a fair amount of work, and somewhere between the commitments of family, work, (and I think even moving), it has been understandably delayed a bit. So we are all living vicariously through you right now. (Although I do have a piece of hardware that I can get a command line interface with StickOS, just not via USB.) There is also a StickOS simulator for PC's lcated here: http://www.cpustick.com/downloads/StickOS.v1.80.exe But the simulator would have different pin names than your hardware.

And as for cheaper, the Eagle board files for the UBW32 are available at Sparkfun's site. Although you sound a bit skeptical (as was I) about soldering a device like that, most others seem to find it very doable, to hand solder these devices (and the rest use toaster ovens). Doing this, with a fair number of boards, would make it much cheaper than the $40 a pop. For soldering tips, check's out nicmus's response here, and Dave's post just after it: http://www.picbasic.co.uk/forum/showthread.php?t=13240&p=92872#post92872

Kenjones1935
- 19th October 2010, 00:19
Thank you rmteo,

I enticed MikroBasic Pro to compile its 1st_project 'blink the LED's' Basic code . I then got PICKit2 to download the resulting .hex file. The only mistake was that MikroBasic assumed the LEDs are attached to PORTC. On the PICKit2 card they are attached to PORTD. After that minor adjustment. It works. :)

KEn!

Kenjones1935
- 19th October 2010, 00:49
Way back I thought a good middle school project would be
to race by R/Cing the car out a door, wait for it to find its way autonomously back through another door (This second door would have a naked 150W bulb at its threshold.), then repeat the cycle some number of times. The R/C - autonomous toggle to be controlled by powering ON and OFF the radio transmitter. If the transmitter's power is ON, the PIC detects activity from the radio receiver and switches control over to the original system.

Advantages of that idea are:
1. No need for proportional controls. A toy level car will do.
2. Photo cells are much less expensive than sonar sensors.

A problem is that the kit requires six DPDT coil driven relays: two for PIC generated steering, two for PIC generated wheel control and two for toggling between PIC control and R/C control. These are inexpensive, but add complexity in kit construction.

This car could also do the swarm-after-teacher who's carrying a naked bright light game. I've been changing my focus from teach-the-student to teach-the-teacher. What do you think? The RC system itself is full of "How things work" answers.

Your thoughts?

Ken

Kenjones1935
- 19th October 2010, 03:22
Wednesday morning I'm going out of town for at least a week. I will not make any robocar progress.

I have one BITWhacker that operates per the documentation. It establishes connection thru the USB and behaves by flashing its lights per "http://www.schmalzhaus.com/UBW32/doc...mentation.html".

The other one has HIDbootloader successfully loaded via PICkit2. It will not make USB contact, it does turn on its LED's, but does not flash them. This too seems to match the above LINK's statements. I have no idea how to get this one back to standard.

My next step is to build that toy level car with the trio of photo cells. Will I need pots to tune each one? I hope not.

Ken

mackrackit
- 19th October 2010, 06:18
POTs would be best to fine tune things but if you are in a very dimly lite room and have a very bright light then you might be able to preset the sensors with fixed resistors.

Kenjones1935
- 19th October 2010, 15:35
My problem loading the BITWhacker PIC32 from PICkit 2 is that it is not capable of doing so. MPLAB tells me that I need PM3, REAL ICE, ICD2, ICD3, or PICkit3.

MichaelS referring to PICkit3 said in a September 2010 entry:

# The application supports all devices supported in MPLAB 8.56 except PIC32. This is not to say it has been tested on all devices. If you have any problems programming any devices, please leave a note here or send me a PM.
# PIC32 support is coming very soon. I have stable support working in my current development builds.



See you in a week or so.
Ken

ScaleRobotics
- 19th October 2010, 16:52
My problem loading the BITWhacker PIC32 from PICkit 2 is that it is not capable of doing so. MPLAB tells me that I need PM3, REAL ICE, ICD2, ICD3, or PICkit3.

MichaelS referring to PICkit3 said in a September 2010 entry:


Yes, MPLAB doesn't like the Pickit2 for use with PIC32, but who needs Mplab to load the Bitwhacker? All you need is the Pickit2 programmer IDE. I get the message saying "Programming Successful", and the command line interface I get after doing so. The Pickit2 is perfectly capable of programming PIC32 chips. Otherwise, it would not have a drop down menu including them. I don't quite know why MPLAB is forcing the use of other programmers, but you don't really have to worry about it.

4862

Kenjones1935
- 19th October 2010, 19:45
My PICkit2 says it works, but the code is not embedded in the chip. I think the problem is with the size of the PIC32 memory. HIDbootloader goes near the front of memory. The high address is 4A20. StickOS goes higher up. StickOS gives me the warning when I try to download it. I have been able to load HIDbootloader, but have not been able to load the OS. At one point I think I got the OS loaded but in so doing it wiped out the bootloader. Of course this is all guess work.

Ken

rmteo
- 19th October 2010, 20:14
I would seriously look at alternatives to CPUStick/StickOS.

Kenjones1935
- 20th October 2010, 01:33
I enticed MikroBasic Pro to compile its 1st_project 'blink the LED's' Basic code . I then got PICKit2 to download the resulting .hex file.

It seems that I can get freeware compiler, but I will be asked to spend $50 each for PICkit2 hardware and software. That is not as bad as the big bucks for PICBASIC PRO restricted to one PC machine per the license.

rmteo
- 20th October 2010, 01:52
Another option I would highly recommend is Arduino (http://www.arduino.cc/), hardware is <$20 and software is free.

Example hardware here Arduino Pro 328 - 5V/16MHz (http://www.sparkfun.com/commerce/product_info.php?products_id=9219)

4863

Kenjones1935
- 31st October 2010, 15:24
There is a big write-up in the latest SERVO magazine on the advantages of Arduino. Maybe.....

I've been thinking..... In my robocar I am controlling rates by measuring scalors. My PIC signals PWM to control rate of speed and rate of turn. Its sonar sensors are giving it distance. My code does not divide by time elapsed. ie differentiate. Is this a basically flawed concept?

I have not been using the BASIC math operators. If I were to work in closing rates rather than pure distance would my error feedback be more appropriate?

Ken

Kenjones1935
- 5th November 2010, 00:23
I need help figuring how to control a robocar at speed. Simply said:

The MODEL level car has proportional control. I preset the max velocity with a POT. I need a robo system that can figure out when to turn given the speed and the distance of oncoming obstacles.

The TOY level cars have only bang-bang controls. Their tires are plastic. They slide and skid. The 1/12 scale car is slow enough for simple sonar distance threshold control. Boring!! The 1/10 scale car is a big fast colorful device: spectacular and fun! With size and speed comes momentum. I need to get better control of the steering (current drivers instead of DPDT relays?) and an algorithm to implement that control.

Any ideas?

Ken

Kenjones1935
- 5th November 2010, 02:51
Some robots first map their environment. If my car were to have a map of the room and could find its location, speed and direction in that room then given constant update of the robot's location and two dimensional velocity it ought to be able to maneuver the wall race. Any ideas how to implement such a scheme? I think the little car will need a compass or something similar. It sure would help if it knew the angle of its motion relative the four walls.

Ken

Kenjones1935
- 5th November 2010, 14:54
The solution is obvious for the MODEL level robocar.

I made the wheel velocity proportional to the POT position. Stopping and turning distance requirements are proportional to speed. Make these distances proportional to the POT also. Easily done.

I have no answer for the 1/10 TOY car aside from making it expensive by implementing a proportional control system.

Ken

ScaleRobotics
- 5th November 2010, 15:57
Hey Ken,

I have heard you say bang-bang a lot describing the turning control for the car. Are you saying that with the remote control that came with the model car, there is no proportional control of the steering, just full right, straight, and full left? Or is there any in between?

Perhaps you could do some testing to see if a pwm signal to the steering would give you some sort of proportional control?

Is this the same for the throttle? On and off, and no in between? Perhaps you could test that as well.

Without any more info, I don't think you can get more than wild guesses. Some pictures of the steering control, and motor control might help as well.

EDIT: Hot off the press. This news from MeLabs:

melabs now offers multi-seat, educational licensing of PICBASIC PRO for schools. Call for details.

Kenjones1935
- 5th November 2010, 19:32
scalerobotics,

1/10 scale TOY level cars cost about $50. 1/10 scale MODEL level cars start at $200. The TOYs are plastic toys. The MODELs are miniature automobiles.

The TOY cars have only [full on / full off] steering and wheel power controls. Their steering servo has two inputs. Three of the four possible states are used:
[A=7v, B=gnd] ==> steer left
[A=gnd, B=7v] ==> steer right
[A=gnd, B=gnd} ==> steer straight (spring loaded)

The corresponding is true for Forward, Reverse, Brake (due to back EMF) for their DC drive motor.

The TOYs have no differential gears, no drive gears at all, no toe in, no caster, no spring suspension, no dampening and plastic tires. They are inexpensive, fast, lots of fun and colorful. They do a great racing skid turn - just turn the wheel and put the motor in brake state. They are large enough to easily accommodate my solderless PIC kit.

The 1/12 TOYs are considerably slower than the 1/10 size. I have succeeded in making one run smoothly around the room hugging the wall. A bit boring.....

I'm off to the old gym to test my MODEL level with velocity and warning distances now all proportional to the position on one POT. Hopefully now all I need to do is find the correct velocity proportionizing formula for each of the SONAR warning distances which are:
frontclear
frontdanger
stopreversing
desiredtrack
outertrack

Ken

cncmachineguy
- 6th November 2010, 00:40
heres my 2 cents. I think I read somewhere in this thread you are driving the steering/drives with actual relays. First thing to do I think is trade them in for H-bridges. Then you will be able to get much higher switching speeds.

next, see if you can get the steering to become semi proportional or at least slower by pulsing the control. I am guessing it is a solinoid and not a motor for the steering. These take time to move fully, so if you can release the signal before the wheels have turned all the way, it will become at least stepped. the springs will smooth out the signals to make it appear proportional.

Now I am sure you can do the same with the drive. Once you have H-bridges in there, you can PWM it :)

Kenjones1935
- 6th November 2010, 01:25
cmcmachineguy,

You are correct. My TOYs use DPDT relays (6msec contact. 4msec release - so they say) driven by SN7407's I have been trying to avoid more electronics. I had hoped to have middle school students build the cars using solderless protoboards and to keep the cost down.... I may need to teach-the-teachers first. They did not major in Science, Technology, Engineering or Math in Ed School. Hmmmm.... In Massachusetts that means hooking up with a local college to give a course which teachers take for "professional development points".

I did find that the TOY steering servos are slow to return to zero. A 50milsec kick to the opposite end gets them started. If I could figure a way to control the kick steer, that would be ideal. It is so spectacular.

I am having a difficult time PIC controlling the MODEL car at cruising speed. This is no where near how fast I can make the car go around the track using the R/C, my eyesight and my coordination.

I took it to the gym today with proportional SONAR thresholds implemented. BIG IMPROVEMENT but still it occasionally hit the wall. Don't know why yet......

Thanks again for the interest and support.
Ken

cncmachineguy
- 6th November 2010, 01:30
Any way you can measure the current for the steering? Maybe it isn't real high and you can use 1 of the DIP H-bridge-on-a-chip. The stall current is what we are after here. Then you would still be able to easily proto board it. Leave the relay on the drive motors.

I suspect if you can get the sterring under control, the drive will become less of a problem

Kenjones1935
- 7th November 2010, 16:30
Today in the mail came two toy store Xmas catalogs. Both feature toy level R/C vehicles. All the more reason my autonomous car for introduction to STEM is a good idea. It may be that we need to teach-the-teachers first.

On the subject of cost. In Fitchburg well over 50% of our public school students come from families that fall below the poverty line. In Massachusetts that means they are eligible for free or reduced price school lunches. If we were to use my cars to teach STEM to middle school kids, it would be nice if they could keep what they build. (Maybe in the context of an after-school program.) If we use my cars to guide teachers toward this corner of STEM through a college supported Professional Development course, again it would be nice if the students could keep what they build.

Here's the question. What games can $50 1/10 scale TOY level cars play given the limitations of bang-bang controls and a 16F887 PIC. As a goal keep the total cost less than $100.

Ken

Kenjones1935
- 8th November 2010, 02:45
The point of my project is communicating "how things work" to pre-teens.

Examples of today's difficulties: My Mom's natural gas powered oven was obvious. Ever try to explain a micro-wave? Souping up a car in my day included high lift cams, carborator changes, tuned straight through pipes. Today the first thing you do to hop up a car is change a computer.

The dashboard on my 2004 GM car told me: "TIRE Pressure LR 23psi LOW". It also said, "TIRE Pressure RR 28psi OKAY". I pumped up my left rear tire. Then the car told me,"TIRE Pressure LR 23psi LOW" and "TIRE Pressure RR 33psi OKAY". WHAT??

The garage mechanic told me each tire valve contains a pressure gauge and enough of a computer to maintain a connection to the car's internal wireless network. A previous owner of my car had rotated the tires. The mechanic also told me that my car, depending of accessories, carries some twenty computers.

It seems to me that the first question in the mind of a future STEM professional is, "How does this thing work?"

Ken

Kenjones1935
- 9th November 2010, 04:23
Today at the gym I got two speed levels to negotiate the wall racing. I have divided my POT's full motion into six steps, 0 - 5. 0 is slowest. 5 is fastest.

Today speed 0 and 2 worked fine. Speed 5 crashed a bit. This evening I increased the proportionality multipliers relating POT position to distance thresholds.

If I can get this car up to speed, imagine racing with more than one on the track.

Ken

Kenjones1935
- 11th November 2010, 22:25
I've added a new video to youtube.

http://www.youtube.com/watch?v=waGlwKBbrEo

Check it out and please give me your advice. I think the car is not responding as fast as it can. I can list an abbreviated version on my code. I may have some fundamental incorrect.

Ken

chuck
- 12th November 2010, 19:33
Hi Ken
I've been watching and reading this thread with great interest and I've got to admire and take my hat off to you for your persistence. Don't give up your nearly there.
Have you used interrupt's in your code ?
If you have not may be the pic cannot proeccess the comamnds quick enough to repsoned. having watching some other video clips they seem to responed really quickly travelling at high speed.
I was thinking of trying my Nitro car but I think that would be to fast.

Kenjones1935
- 12th November 2010, 22:32
chuck et al,

My code has no interrupts. It loops through poling the sonars many times per second. They flash a red led when poled. This is visible.

I use HPWM to generate the controlling signals. This is a stretch. The spec calls for one pulse each 20 msec. With the standard oscillator the PIC can't go that slowly. I learned what works by trial and error.

When controlling the car using R/C I can make it behave at faster speeds than the PIC can. Why? It might be that the feed back loop through my eyes and fingers is inherently better. My PIC code only works with distances. My eyes and brain work with distance and rate (of closing speed and steering).

Want to see some code?

Ken

Kenjones1935
- 12th November 2010, 22:37
I have been wondering whether the HPWM code starts fresh each time it is called. My system calls it after every SONAR poling. This is many times per second. Could it be that each time HPWM is called it pulls the output pit down in order to create a new pulse stream and in so doing screws up the pulse stream it had been sending.

Ken

chuck
- 13th November 2010, 01:19
Ken yes I would like to see some of your code,
I'm not sure about the HWPM resetting, If I understand correct the pic is monitoring the distance so when it comes close to the object this decreases the HPWM signal ? to reduce spped and turn the wheels at the same time ?
Are you sure that the pic to calaculating the distance fast enough to react with the object ?

I would say that interrupts would be able to act faster than the standard code. it would be nice if you could see how fast the HPWM command is reacting or so fast the pic is processing the data fast enough from the SONAR's

Kenjones1935
- 13th November 2010, 02:15
Thanks everyone.

The speed of PIC calculations can be judged by the rapidity of the flashing LED on the SONARs. My code just goes round and round. This is very visible when I run the car without its skin. It flashes so fast as to hardly be blinking. At least every 100 msec.

Here's the action part of my code. If you like I can include the constants, pin selections etc.



main:
'pause 10 'Assure ringing from previous triggers: are gone.
GOSUB triggers
'-------------------
CheckIfInDanger:
IF rangefront < frontdanger THEN
HPWM 1,Straight,50
HPWM 2,Back,50
PAUSE 250
reversing = 1
GOTO reverseoutoftrouble
' loop till this is secured
ENDIF
'-------------------
tryleftturn:
IF rangefront < frontfree THEN
'something ahead - turn hard left.
HPWM 1,Left,50
HPWM 2,HalfForward,50
steeringleft = 1
GOTO main 'loop till this is secured
ENDIF

'-------------------
goingforward:
HPWM 1,Straight,50
HPWM 2,Forward,50
'-------------------
keepgoingforward: '----Compare to right wall
IF rangeright > outertrack THEN
HPWM 1,QuarterRight,50
ENDIF

IF rangeright < desiredtrack AND oldrangeright < rangeright THEN
HPWM 1,Straight,50
ENDIF

IF rangeright > desiredtrack AND oldrangeright > rangeright THEN
HPWM 1,Straight,50
ENDIF

IF rangeright > desiredtrack AND oldrangeright < rangeright THEN
HPWM 1,QuarterRight,50
ENDIF

IF rangeright < desiredtrack AND oldrangeright >= rangeright THEN
HPWM 1,QuarterLeft,50
ENDIF

GOTO main
'-------------------------
reverseoutoftrouble:
GOSUB triggers
WHILE rangefront < stopreversing
HPWM 1,Right,50
HPWM 2,Back,50
GOSUB triggers
WEND

IF rangeright > outertrack OR rangeright < desiredtrack THEN
HPWM 1,Left,50
steeringleft = 1
HPWM 2,HalfForward,50
ENDIF
GOTO main
'--------------------------

triggers: ' Check three sonars and channel 3 signal.
oldrangeright = rangeright
' produce 10uS trigger pulse (must be minimum of 10uS)
LOW trigright
HIGH trigright
HIGH trigright
HIGH trigright
LOW trigright
'zero could be legal below
PULSIN echoright,1,rangeright 'measures the range in 10uS steps
PAUSE 10 'Wait for ringing to stop - read SF05 spec.

pulsf:
oldrangefront = rangefront
LOW trigfront
HIGH trigfront
HIGH trigfront
HIGH trigfront
LOW trigfront
PULSIN echofront,1,rangefront ' measures the range in 10uS steps
PAUSE 10

Checkpot:
' I think Potread goes from 0 to 6.
ADCIN PORTA.0, Potread
Potread = Potread/37
Forward = 105+Potread
HalfForward = 105+(Potread/2) 'seems to work.
Back = 95-Potread
HalfBack = 95-(Potread/2)
'----------
frontdanger = 210 + Potread*55 '210-540, 14-36 inches
stopreversing = 180 + Potread*25 '180-330, 12-22 inches
frontfree = 700 + Potread*60 '700-1060, 48-70 inches
desiredtrack = 180 + Potread*20 '180-300, 12-20 inches
outertrack = 360 + Potread*15 '360-450, 24-30 inches
'-----Below worked for Potread = 0and2. Not for 5
'frontdanger = 210 + Potread*50 '210-510, 14-34 inches
'stopreversing = 180 + Potread*25 'Fix backup confusion
'frontfree = 700 + Potread*50 '700-1000, 48-72 inches
'desiredtrack = 180 + Potread*12 '180-252, 12-16 inches
'outertrack = 360 + Potread*12 '360-432, 24-28 inches
'----------
'record for posterity
WRITE 2, WORD Potread
WRITE 4, WORD frontdanger
WRITE 6, WORD stopreversing
WRITE 8, WORD frontfree
WRITE 10, WORD desiredtrack
WRITE 12, WORD outertrack


'***********************
checkchannel3:
'works with four AA batteries pack.
'Radio receiver puts pulses
'on this line whenever the transmitter is turned ON.
switchtoPIC = 2
WHILE switchtoPIC >= 2
COUNT channel3,65,switchtoPIC
HIGH portc.0
WEND
LOW portc.0
RETURN

END

chuck
- 13th November 2010, 08:55
Thanks Ken I will have a read through your code to get to understand it

Regards,
Chuck

rmteo
- 14th November 2010, 01:06
Ken, there are 2 issues that have not been addressed since the beginning of this project.

1. The less serious of the 2 is your use of the hardware PWM module. R/C devices, such as servos and ESC's, expect a control pulse (typically 1-2mS) at about 50Hz. You can probably go lower to 30Hz or higher to about 100Hz and things should still work fine. However, a PIC16 with a 20MHz clock (which I believe you are using) will not go below 1220Hz (PR2=0xff). Even with an 8MHz clock the lowest is 488Hz (244Hz with a 4MHz click) and is still probably to high compared to the desired 50Hz.

2. To get a closed loop control system to work correctly, you need more than a bunch of if-then-else statements. Ideally you want to use a PID controller. A proportional-integral-derivative controller (PID controller) is a generic loop feedback mechanism. It measures a process variable (e.g. temperature), and checks it against a desired set point (e.g. 100 degrees Celsius); it then attempts to adjust the process variable by changing a controller output (e.g. PWM signal to an electric heater) which will bring the process variable closer to the desired set point. Even a simple P (proportional only) controller would be much better than what you currently have.

Kenjones1935
- 14th November 2010, 01:58
I have been wondering whether I have a basic mistake in my feedback loop. I am measuring distance and adjusting rate of speed and rate of turn. Maybe I should be measuring rates not scalars

This means differentiating. I would need to measure two distances a fixed time apart. Then do some subtraction. I do that a little bit in my code, when I include "oldrangeright" in my state machine, but since there is no consistency to my sample time...... Rate of turn is even less clear.

Is this the PID flaw you are suggesting? What is the solution? What are the technical limitations? Will a 16F887 do the job? Do I need C code including appropriate libraries? I do not know how to start.

Your comments about my PWM are true. I found what works by trial and error. To get 50hz would I need to install an outside oscillator? Might I somehow divide down the internal one?
Ken

Kenjones1935
- 14th November 2010, 02:17
I think you are telling me that I have not been using my PWM mechanism. In the case of turning I have defined STRAIGHT QuarterRIGHT, HalfRIGHT, RIGHT and the corresponding for LEFT. (I did not show you folks my definitions.) But I only use STRAIGHT, RIGHT and LEFT. That's bang-bang like a TOY level car. I could be doing much finer adjustments if I did a bit more arithmetic on my SONAR readings. GOOD IDEA. GOOD OBSERVATION. Presently I do comparisons in HEX. I really don't want to waste time translating to decimal.

Thank you!!

Ken

Kenjones1935
- 14th November 2010, 14:38
I can not imagine a cheapo device that will measure closing rate.

Can a robot know closing velocity other than by measuring distances at specified time intervals and divide? Anybody seen this done with PBP (or C or C++) on a PIC? Is this the reason I will have to upgrade to a 32MX460? I would love to see sample code.

Ken

rmteo
- 14th November 2010, 15:42
Have you fixed the easier of your 2 issues yet? Expecting it to work correctly at 1220Hz when it is waiting for 50Hz may be a bit of a stretch. You can create a multi-channel, interrupt-driven, software PWM with a PIC16 and a 16-bit timer - such as TIMER1. If you don't know how to do that, then select a PIC18 and use DT's 2-CH Hardware Servo Driver (see CMS articles on the right of the HOME page). It is limited to only 2 channels but will work for your project for now.

When you have that working correctly, then you can progress to the PID stuff which looks like this:
4944

ScaleRobotics
- 14th November 2010, 16:47
When you have that working correctly, then you can progress to the PID stuff which looks like this:
4944

Hey RMTEO,

Don't be shy about posting actual code. We would love to see your PBP example of the above. :D

rmteo
- 14th November 2010, 17:48
Hey RMTEO,

Don't be shy about posting actual code. We would love to see your PBP example of the above. :D
Hey SCALREOBOTICS,

What made you think that I was going to do that in PBP? I do not think that PBP would be the way to go for Ken's situation but I would be happy to have you prove me wrong. :D

mackrackit
- 14th November 2010, 17:58
Hey SCALREOBOTICS,

What made you think that I was going to do that in PBP? I do not think that PBP would be the way to go for Ken's situation but I would be happy to have you prove me wrong. :D

Then why would you suggest that Ken do it? Other than to add more confusion or a chance to say something else is better.

Why do you not post something to try helping. Always posting that another compiler is better is not a help. Other compilers might be better but that is not the issue here.

So I will ask you to not to post on this forum if that is all you have to say.

ScaleRobotics
- 14th November 2010, 18:27
Hey SCALREOBOTICS,

What made you think that I was going to do that in PBP?

Uh ....... in case you didn't notice, this is a PicBasic forum. That would be what is spoken here. Each language that you recommend have their own forum. And we don't go there talking about PBP, do we?

rmteo
- 14th November 2010, 19:38
Ken, good luck with your project.

Kenjones1935
- 15th November 2010, 03:33
rmteo's comments DO help. I went to WIKIPEDIA and looked up PID and pretty much understand what it is - sort of. It ain't so complicated as the single formulaic representation makes it appear.

Question about PBP and my 16F887. I think the spec for my robocar says to produce one PWM pulse every 20 msec. Each pulse varying in width from 1 to 2 msec in 256 segments. A 1.5msec (created by 127 segments) pulse is neutral. In the case of my Electronic Speed Control anything above 1.5msec is FORWARD. Anything shorter than 1.5msec is BACK. What must I do to scale my chip's 4MHZ oscillator to accomplish this fete?

What I am presently doing I came across by trial and error. I am not sure what shape the PIC is actually producing.

Ken

mackrackit
- 15th November 2010, 03:59
Lets go back a little
http://www.picbasic.co.uk/forum/showthread.php?t=12039&p=94621#post94621

Kenjones1935
- 15th November 2010, 14:55
I have not learned to SEARCH the forum.

How about I return to basics. How about I make my controls interrupt driven. If had an interrupt routine that ran every 20msec, I could create a true-so-spec PWM signal and I could measure rate of closing speed for each SONAR. I think the 16F887 can get all my work done in 20msec. If not I can up the PIC power.

Way back someone told me how to set up such an interrupt system. Where is that? It's Monday morning. Time to get moving.

Ken

ScaleRobotics
- 15th November 2010, 15:21
Here are some that were referenced in the thread. None of them use your chip though, so some modifications would need to be made, or changes to a new chip.

A 12F683 design (would require a fair amount of changes to work on your chip)
http://www.picbasic.co.uk/forum/showthread.php?t=12039&p=84998#post84998

This one could not be modified for your chip, and would require a 18F2431, or 4431.
http://www.picbasic.co.uk/forum/showthread.php?t=12039&p=91961#post91961 (cleaner code than above)

And the one rmteo pointed out, which would require an 18 series chip: http://www.picbasic.co.uk/forum/content.php?r=253-2-CH-Hardware-Servo-Driver (Darrels, so you can't really go wrong)

Once you decide which way you would like to go, I am sure we can help you get it going.

Kenjones1935
- 15th November 2010, 20:44
My video shows my kit uses a 0.1" centers solderless prototype board. If I am to change PICs I would like something compatible.
I tried the 32BITWhacker board of 32MX460. I was disappointed because I could not program it using the PICKIT2 system. Maybe if I purchase a PICKIT3.....(It is programmable via its USB port. That requires I completely change my coding system and learn yet another variation of BASIC or C)

What Microchip PIC do you all suggest that has a Dual Inline (DIP) configuration and is easily programmable?

Ken

Kenjones1935
- 15th November 2010, 21:56
The BITwhacker is appealing because it has 0.1" center holes. All I need to do is solder male to male connectors and stick the whole shebang into a solderless protoboard. It is a bit large for the HPI SPRINT R/C car. I never got the BITwhacker to work. (I purchased two. One came with a teeny tiny slide switch in the wrong position. That led me on a wild goose chase which ended up with one BITwhacker losing its embedded STICKOS code. The other board is good as new, but now I am leery of the whole thing.

Is there a MIcrochip and/or MicroEngineering Labs product that works in a predictable fashion with the BITwhacker?

If not the above then I need the schematic of a starter kit showing how a powerful-enough-to-do-my-job DIP configured PIC is hooked up to either a classic USB port or the RJ11 Microchip USB adaptor. The I need a PC based compiler that will do the job and a programmer that will load the resulting code into the PIC.

Suggestions??

Ken

cncmachineguy
- 15th November 2010, 22:25
Ken, Here is what I think.
I agree with going back to the basics. As I have been reading this thread since your project started, I for 1 am not real sure where you are with methods, hardware, program,...

I suggest you do this: List all the parameters needed. such as how long does the sonar need to accquire a distance? How many things does the PIC need to do? Then you will be able to determine if your chosen PIC is up to the job.

I think it prolly is, and I think PBP is also up to it. Worst case is to sprinkle some ASM in if needed.

Kenjones1935
- 16th November 2010, 03:06
The SONARs each get a 10micro sec trigger. This creates an ultrasound PING. I use PULSIN plus PAUSE 10 to input the response and wait for the ringing to stop. Total time for two SONARs = at least 20msec.

To make room for the PWM pulses I could shorten the length of the SONAR PAUSEs. Trying to fit 20msec interrupts clearly might be a problem.

I could trigger the SONARs less often (interrupt driven). I do not need to be measuring the distances so often. The PIC could, at that time, skip a PMW interrupt - or delay it a couple of milliseconds.

Other than that all the code does is fly through various IF THEN state machines depending on the most SONAR readings. That is very simple.

However-----\

If I could calculate closing rates accurately and if I had a finely tuned proportional control system then I might be able to implement a real PID system. Not sure. I do not know how to analyze this.

Ken

mackrackit
- 16th November 2010, 03:22
Thank you for the October reference.

I have not learned to SEARCH the forum.

??????
No search required for that, it is a part of this thread.

Anyways, have you looked over the PID routines given by Henrik Olsson?

cncmachineguy
- 16th November 2010, 03:42
The SONARs each get a 10micro sec trigger. This creates an ultrasound PING. I use PULSIN plus PAUSE 10 to input the response and wait for the ringing to stop. Total time for two SONARs = at least 20msec.


hate to be picky, but is it micro or milli seconds?
Can both sonars be active at the same time?


If I could calculate closing rates accurately and if I had a finely tuned proportional control system then I might be able to implement a real PID system. Not sure. I do not know how to analyze this.
Ken

Maybe I am just lucky at times, but i have never been properly introduced to a real PID system. I don't consider myself being able to emulate a PID when I am flying R/C planes, yet I can fly them. The finely tuned proportional control system is not too hard, I am sure we can get you there.

Kenjones1935
- 16th November 2010, 03:45
Yes, I looked at Olsson's routines. I got distracted by the thought that my 16F887 is just not up to the task at hand.

I glanced through the MicroChip 18F PICs. My eye fell on the PIC18F46K20.
It comes in 40 pin PDIP format. That is good. It has lots more code memory space. It is on the list of devices that can be programmed by my PICKIT 2 and my Microcode Studio PICBASIC PRO combination. It must be bigger, faster, more capable than my 16F887. True? Which 18F should I choose. I have little to no sense of the differences.

Ken

cncmachineguy
- 16th November 2010, 04:17
Ken, What makes you think your current device is not up to the task? R/C systems are very slow IMHO relative to processors. Think on this, pulses for the car happen for 1-2msec each every 20 msec. so 2 pulses (drive & steering) will be max 4 msec. That leaves 16 msec for the uP to do whatever like measure distance and decide what to output next. At 4Mhz clock, thats 16000 ASM instructions! Not PBP instructions but still a whole lot!

So heres a couple of thoughts: Use pulseout for the signals to the car. No need for int or PWM. How about connecting 1 of the car signals from the receiver to your pic. Then just check to see if the pin went high, if so its time to send out commands. This way you can use the car receiver as a 20mSec clock.

mackrackit
- 16th November 2010, 04:17
I do not have any experience with the 18F46K20 but two things that I think would make it a good one for this project are:

Internal Oscillator Block:
- 8 user selectable frequencies, from 31 kHz to
16 MHz
- Provides a complete range of clock speeds
from 31 kHz to 64 MHz when used with PLL
And

Enhanced CCP module: In PWM mode, this
module provides 1, 2 or 4 modulated outputs for
controlling half-bridge and full-bridge drivers.

ScaleRobotics
- 16th November 2010, 14:39
I also think the PIC16 or 18 is plenty fast for the application. But the servo's and speed controllers are pretty picky about their signals. They need to be at regular intervals in order for the servo's and speed controllers to work smoothly. Otherwise their operation can be erratic. While you could measure the receiver with pulsin, I would stick to interrupts for the servo and speed controller. The PIC18F4431 has hardware that allows for R/C pwm frequencies. But it could be done with pretty much any PIC using spwm. I would probably use a PIC18 rather than a PIC16 because it opens up a couple of possibilities, but both are powerful enough.

cncmachineguy
- 16th November 2010, 15:53
Hi Walter, quick question. I am under the impression most Rx send their pulses sequencially, so when channel 1 is done, 2 starts, 2 done 3 starts... I know they are not always in numeric order, but none the less they wait until the last is don befor sending the next. At least with a little older equipment.

If my assumption is correct, in a 4 channel Rx, channel 4 could start anywhere between 4mSec to 8mSec after the start of the 20mSec frame. (channel 1,2 and 3 could be all min or all max). If this is true, They can't be too picky cuz 4 mSec is pretty darn big!. I would think it would take little effort to hit the 20mSec loop within .1msec.

so I was thinking in the main loop, don't measure the pulse from the Rx, just see if it went high. Then within a couple of instructions the "send pulses" routine would start. When thats done, acquire the next distance reading (10 mSec) then back to the old main loop waiting for the next trigger from the Rx.

Of course if my assumption is not correct, this was a nice typing excerise for me :)

Kenjones1935
- 16th November 2010, 20:39
1. Although the SONAR only requires a 10microsec trigger pulse, at 1100 feet per second a five foot sound echo returns (order of magnitude) in a bit less that 10 millisec. I can not trigger both SONARs at the same time. I believe their echos would interfere. I certainly do not have to trigger these devices 50 times per second. Three or four times per second would be enough. This would give the velocity rate calculations more meaning. (Maybe I should make the SONAR activity interrupt dependent, not the PWM activity.)

2. The PIC needs to control the steering. It needs to keep the car traveling parallel to the side wall a given distance (desiredtrack) from that wall. It also needs to turn the car dramatically left when a (corner) wall appears inside a given distance (frontfree) in front. Both 'desiredtrack' and 'frontfree' are VAR WORDs - functions of the POT position (which also influences the speed of the car).

3. There is a totally separate algorithm controlling steering when the car is backing up due to a collision or a very near miss. Basicly steer right and back up a couple of feet then steer left and try to go forward.

4. If the steering were absolutely under control I feel the wheel speed could be pretty much left alone. Check the POT and make the PWM signal to the Electronic Speed Control proportional in seven stages.

5. My PIC really should have four pieces of data to work from.
A. Distance to the right wall.
B. Closing rate to the right wall.
C. Distance from an object in front.
D. Closing rate on the object in front.
If it had this information I think even I could code proportional feed back loops. Note two are rates. Each of these require two readings a known time apart, a subtraction process and some comparisons to fixed estimated values.

6. My model level car can be put under radio control merely by turning on the power to the ratio transmitter. It is selection which PWM signals (radio receiver sourced or PIC sourced) that is done by the DPDT coil driven relay switch. It is driving that relay switch coil that requires the SN7407 current driver.

7. I chose the HPWM to shape the steering and DC motor signals because by trial and error I found parameters that seemed to work at slower speeds. The signals continue no matter what the PIC code is doing. I do wonder whether I screw up a sequence each time I exercise a new HPWM command even if it is a repeat of the previous HPWM command. I do not understand the architecture details of HPWM command.

Ken

Kenjones1935
- 16th November 2010, 20:54
Originally I used a three channel R/C system. I kept the transmitter on all the time. Like you all suggested I could have used its outputs to trigger the PIC's PWM signals.

To take R/C control I tuned on channel 3. The receiver signaled the PIC that channel 3 was active. The PIC flipped the DPDT relay thereby steering the radio receiver's servo signals to the car.

This was not a good system because the model level car which is the basis of my work comes naturally with a 2 channel R/C. Adding the third channel was a big expense. Too much for our school systems.

Ken

Kenjones1935
- 16th November 2010, 21:41
From what I can tell the PIC18F45K20 is compatible with the PICKIT2 and MPLAB systems. I see that it comes in a 40 pin PDIP configuration.

Do you think I could unplug my 40 pin PIC16F887 and plug in a new PIC18F45K20 40 pin PDIP, do a bit of rewiring and be ready to go hardwarewize?

KEn

cncmachineguy
- 17th November 2010, 00:38
What does it give you that you don't have with the '887?

Kenjones1935
- 17th November 2010, 01:48
Scalerobotics wrote a while back:


A 12F683 design (would require a fair amount of changes to work on your chip)
http://www.picbasic.co.uk/forum/show...4998#post84998

This one could not be modified for your chip, and would require a 18F2431, or 4431.
http://www.picbasic.co.uk/forum/show...1961#post91961 (cleaner code than above)

And the one rmteo pointed out, which would require an 18 series chip: http://www.picbasic.co.uk/forum/cont...e-Servo-Driver (Darrels, so you can't really go wrong)

I am not enough conversant with the various Microchip models to talk intelligently about what I need or don't need.

Ken

Kenjones1935
- 17th November 2010, 02:32
After comparing the power and the 6 pin PC connector selections of the 44 pin 16F887 in the PICKIT2 and the 44 pin 18F45K20 in its StarterKit I think I can unplug one and plug in the other. I'll bet that will be the same for the 40 pin PDIP versions also. Good for our team.

Ken

cncmachineguy
- 17th November 2010, 02:38
ken, I think you should stick with the '887. You already have lots of experience with it and really it can suit your needs just fine.

If you want to jump up to the 18F, you may find yourself feeling like WOW, how do I do this. From what I have found, the 18F's just left me feeling like I had just stepped into a new world with regards to setting up and configuring it just to get it to run. You are doing basic stuff, ie no USB or 4 way PWM with encoder feedback. So the 887 can do that just fine.

BTW, I don't remember how fast you are running the PIC. Whats your osc speed?

Kenjones1935
- 17th November 2010, 04:07
My oscillator is 4Mhz (I think). I have done nothing to change it. Whatever it does naturally is what it is.

My guess is that SONAR triggering four times per second is sufficient.

Question: How do I create an interrupt every 1/4 second?

Ken

ScaleRobotics
- 17th November 2010, 05:44
Hi Walter, quick question. I am under the impression most Rx send their pulses sequencially, so when channel 1 is done, 2 starts, 2 done 3 starts... I know they are not always in numeric order, but none the less they wait until the last is don befor sending the next. At least with a little older equipment.

If my assumption is correct, in a 4 channel Rx, channel 4 could start anywhere between 4mSec to 8mSec after the start of the 20mSec frame. (channel 1,2 and 3 could be all min or all max). If this is true, They can't be too picky cuz 4 mSec is pretty darn big!. I would think it would take little effort to hit the 20mSec loop within .1msec.

so I was thinking in the main loop, don't measure the pulse from the Rx, just see if it went high. Then within a couple of instructions the "send pulses" routine would start. When thats done, acquire the next distance reading (10 mSec) then back to the old main loop waiting for the next trigger from the Rx.

Of course if my assumption is not correct, this was a nice typing excerise for me :)

Hello Bert,

I think all your assumptions are correct.

What I have seen is when pulses of 1 to 2 ms are not timed to occur about every 20 ms, the servos exhibit some eratic behavior. If some timing is attempted, and you get close-ish to the 20 ms the servo's are expecting, then yes, you will probably be just fine. But if you are going to go to the trouble of getting the timing close, why not use interrupts? It would allow the pic to be looking at different sensors, and not make it "dead" for up to 4 ms (1/5 of the time) while it sends out a pulse to two servo's.

mackrackit
- 17th November 2010, 05:51
This is very helpful.
http://www.picbasic.co.uk/forum/content.php?r=159-New-PIC-Utility.-PICMultiCalc

Probably the easiest way to get started is with ON INTERRUPT. It is not the most accurate, it will only interrupt when nothing else is going on. Sound silly but..
An example would be a long PAUSE, the ON INTERRUPT will flag and run when the PAUSE is finished. ASM interrupts or DT's instant interrupts will work as true interrupts, but for your case ON INTERRUPT should be close enough.

This should be close. Run it on your board and see what happens.

'FL PIC16F887
'16F887 INT RUPT
'44 PIN DEMO BOARD
@ __config _CONFIG1, _INTRC_OSC_NOCLKOUT & _WDT_ON & _MCLRE_OFF & _LVP_OFF & _CP_OFF
INTCON.5 = 1
OSCCON = %01110000 '8 Mhz
DEFINE OSC 8
OPTION_REG = %01000111 ' 1:256 PRESCALE
ON INTERRUPT GOTO TLOOP
CNT VAR BYTE
D VAR BYTE
D = 0
DATA @10,10,20,30
TCNT VAR BYTE

START:
FOR CNT = 0 TO 150
PWM PORTD.7,D,10
D = D + 2
NEXT CNT
GOTO START

DISABLE
TLOOP:
TCNT = TCNT + 1
INTCON.2=0
IF TCNT = 8 THEN
TOGGLE PORTD.4
TCNT = 0
ENDIF
RESUME
ENABLE

cncmachineguy
- 17th November 2010, 13:38
I agree walter, if going to the trouble, why not be correct.

Ken, heres something I was thinking,
Set up a 5msec interupt timer.
on each int, increment a counter
first count (@5msec) ping sonar 1
second count (@10msec) update servos
third count (@15msec) ping sonar 2
fourth count (@20msec) reset counter, write things (from looking at your code), adjust pulse times for next servo update.

so your int handler will do:
reload timer, inc counter, clear jump flags, retrun

main will do something like this:
if counter =1 and sonar1flag=0 then ping sonar 1
if counter =2 and update flag=0 then updateservos
if counter = 3 and sonar2flag=0 then ping sonar 2
if counter =4 and mathflag=0 then math stuff

in each subroutine first thing to do is set the flag, then do the routine.

Kenjones1935
- 17th November 2010, 17:29
cncmachineguy

Five millisec interrupts seems like a good plan. I will do a little more complicated counting and skipping. I think the SONARs should be less often if I am going to calculate velocity.

I wish I felt more at home with PBP. I'm tempted go to the freebe C, but that means starting all over again. It's been too many years.... Too lazy. sigh...

How do I get 5millisec interrupts from a FOSC/4 oscillator. I just do not understand section 6.0 of the '887 spec sheet.

Ken

cncmachineguy
- 17th November 2010, 19:36
cncmachineguy

Five millisec interrupts seems like a good plan. I will do a little more complicated counting and skipping. I think the SONARs should be less often if I am going to calculate velocity.
I'm not sure what needs to be more complicated, but I am prolly not seeing the whol picture. Velocity calc won't take long, I am sure it can still be done in the fourth block You have 5000 cycles to burn up before the next interupt.


I wish I felt more at home with PBP. I'm tempted go to the freebe C, but that means starting all over again. It's been too many years.... Too lazy. sigh...

I don't have any experience with PBP yet (but I will start programming in the next week or so :) ), all my programming has been in ASM. But from what I can see, there may be a few times when PBP isn't the best choice, but I don't know when that is. All languages have pros and cons. PBP seems to me to be a very good compilier. If I were you, I would just stick with it. I don't think it is where the difficulties are.


How do I get 5millisec interrupts from a FOSC/4 oscillator. I just do not understand section 6.0 of the '887 spec sheet.
Ken

For my part of being lazy, its not going to look at the datasheet for this processor. But the good news is I don't think I need to to answer this. I assume '887 has at least 1 16 bit timer you are not using. So go look at the timer section and figure out how to configure it as a counter. What I find to be the most important part about osc is this, it takes 4 clock cycles to execute an instruction (ASM). So that means if using 4Mhz clock, each instruction takes .000001 seconds, or 1/(osc/4). so for 5 msec, thats 5000 instructions. The timer/counter will increment 1 for every instruction. So heres the math:
16 bit counter = 65535
65535 - 5000 = 60535

so if you preload the timer with 60535, it will take 5000 counts to roll over. thats 5 msec. If timer overflow interupt is enabled, an int will be generated at 5 msec. Then in the handler, reload the timer with 60535 so another int will happen in 5 more msec. and so forth.

1 thing to keep in mind, 60535 assumes there is no lag between rollover and reload. In reality there is, it will take a few cycles to enter the interupt, then another few to reload and start the timer. so your number would adjust up by some small amount. for instance: if it takes 12 cycles to go from overflow to reload, the number you want to load would be 60535 + 12 = 60547. Make sense?

You can determine the exact number with some testing, before you reload the timer, grab the timer low byte and save it. then look at that number. it will be the number of cycles it took to get to the point where you grabbed it. Then replace the code to grab it with code to load it and the timing should be within 1 or 2 cycles.

I will let you chew on this for a while.
BTW, If you find there is not enough time between int for math and such, change the clock to 8Mhz, then you will be able to execute twice as many instructions between interupts.

Kenjones1935
- 18th November 2010, 03:32
There are plenty of machine cycles to do the math work and the control decisions. I think the 5 millisec interrupt timing should give me accurate timing for the PWM signals. I have no idea how much noise there is in the SONAR responses. I want to space them further apart in time so the trends are clear. Four triggers for each SONAR per second is my first guess.

Now to bed. Thanks.

Ken

Kenjones1935
- 18th November 2010, 15:14
Folks, I have been PBPing on a wing and a prayer (to quote an old WWII song). I need more
reference material. I compiled Mackrackit's code and got the following error. I do not know
where to go to chase it down.

Error 118 c:/~~~.asm 67: Overwriting previous address contents(2007)

Here's from the .asm file:

66 ASM?
67 __config _CONFIG1, _INTRC_OSC_NOCLKOUT & _WDT_ON & _MCLRE_OFF & _LVP_OFF & _CP_OFF
68
69 ENDASM?

mackrackit
- 18th November 2010, 15:22
Remove this line

@ __config _CONFIG1, _INTRC_OSC_NOCLKOUT & _WDT_ON & _MCLRE_OFF & _LVP_OFF & _CP_OFF
The above sets the configs in code space. You must be setting them in the *.inc file. Either way is good.

To read more about it
http://www.picbasic.co.uk/forum/content.php?r=157-Presetting-Configuration-Fuses-(PIC-Defines)-into-your-Program

cncmachineguy
- 18th November 2010, 15:40
There are plenty of machine cycles to do the math work and the control decisions. I think the 5 millisec interrupt timing should give me accurate timing for the PWM signals. I have no idea how much noise there is in the SONAR responses. I want to space them further apart in time so the trends are clear. Four triggers for each SONAR per second is my first guess.

Now to bed. Thanks.

Ken
Ken, I have been thinking about this, and IMHO the cleanest way may be to use 2 counters, one for the math/pwm, and 1 for the sonars

Kenjones1935
- 18th November 2010, 16:09
The PWM development works. Clearly LED #7 grows in magnitude through eight counts of #4.

The PWM is controlling the frequency of that signal's pulse. I do not unerstand
how the prescaler and the 8Mhz clock create the slowly blinking LED4.

KEn

cncmachineguy
- 18th November 2010, 18:05
There are plenty of machine cycles to do the math work and the control decisions. I think the 5 millisec interrupt timing should give me accurate timing for the PWM signals. I have no idea how much noise there is in the SONAR responses. I want to space them further apart in time so the trends are clear. Four triggers for each SONAR per second is my first guess.

Now to bed. Thanks.

Ken
I think once you have the PWM stuff sorted in your head, I feel like you may need to address this not knowing part. If your car is going a mere 10 mph, that's approx 14 feet per sec. If you only check each direction (front and side) four times a sec, your car will have traveled 3.5 feet!!! Ok maybe you are not going 10, but how bout 2 mph? That will still be 7.5 inches. At that rate, you will be correcting for things long past.

Kenjones1935
- 18th November 2010, 19:09
I have been forgetting that this car is capable of mph. Not just 10, but over 20. I am pushing some boundaries. I know nothing theoretical about control math. My gut tells me that knowing rate (ie trend) is of great importance -- somehow.....

Ken

ScaleRobotics
- 18th November 2010, 19:31
Great point Bert.

Ken, can you remind me again, what sonar sensor you are using? Parallax's sensor looks like it can do just about every 20ms. But not sure what it will do with echos that are further away. But I don't think you are using their sensor, so it probably has different specifications.

Walter

cncmachineguy
- 18th November 2010, 20:05
Ken, I really don't know much about control math either. I tend to think of things as instant. So at some point This whole thing may very well go over my head. FWIW, I am thinking about your sensors as if they were a gyro on an R/C copter. The gyros watch for any movement not commanded by the Rx. when this happens, they instantly modify the signal to the servo to correct and bring the controlled axis (usually the tail) back to where it was. The more movement the harder it tries to bring it back. Now if we think about this in terms of a little older equipment, this can only happen every 20 msec. but that is plenty fast enough to keep the tail looking rock steady.

With your car, I look at it like this: if you want to maintain a distance, say 12 inches from the right wall, every command to the steering will have some adjustment in it to keep it there. Sensor takes a distance-wall is 11.9" away, turn left a little. next loop, wall is still 11.9 turn more. next loop, wall is 12.02", turn back.

Same with the front wall, except for the amount to turn will need to be more because the wall is approaching. the side sensor will also need to know it should expect to move away from the wall and not fight the front sensor.

Kenjones1935
- 18th November 2010, 20:09
Here's the WEB page for my SONAR SF05.

http://www.robot-electronics.co.uk/htm/srf05tech.htm

It says:
-10microsec trigger pulse
-produces an 8 cycle burst of 40khz sound (total duration 5millisec)
-can be triggered every 50millisec (20 per second)
-the beam pattern is conical.

Details! Details! Ain't technology grande!
Ken

Kenjones1935
- 18th November 2010, 20:22
cncmachineguy,

I sort of tried to do what you say:


goingforward:
HPWM 1,Straight,50
HPWM 2,Forward,50
'-------------------
keepgoingforward: '----Compare to right wall
IF rangeright > outertrack THEN
HPWM 1,QuarterRight,50
ENDIF

IF rangeright < desiredtrack AND oldrangeright < rangeright THEN
HPWM 1,Straight,50
ENDIF

IF rangeright > desiredtrack AND oldrangeright > rangeright THEN
HPWM 1,Straight,50
ENDIF

IF rangeright > desiredtrack AND oldrangeright < rangeright THEN
HPWM 1,QuarterRight,50
ENDIF

IF rangeright < desiredtrack AND oldrangeright >= rangeright THEN
HPWM 1,QuarterLeft,50
ENDIF

GOTO main

I have three degrees of turning in each direction. My "oldrangeright" WORD is the previous reading of that SONAR. What I had not done was make this state machine "math" actually proportional. My present thinking is that with finer control I would get smaller oscillations.

Ken

Kenjones1935
- 18th November 2010, 21:14
I have avoided translating to digital any of my measurements. I have used > and <, but no actual arithmetic. To go proportional per the PID, requires that I do arithmetic. HEX or digital, that is the question. I'd like to think in digital, may I?

I'm going to reveal my age. I wrote in machine language on the IBM 370 back in the last century. Well back in the last century. Since then it has been C, C++, shell, tcl. I am used to having a large library backup and writing in a modular fashion. Now it is PBP. I think I need to know more about ASM coding and the architecture of the PICs. What is the easiest (best) way to learn?

Ken

Kenjones1935
- 19th November 2010, 14:54
cncmachineguy, TIMER1 interrupt with a carefully chosen pre-set sounds good to me. I am not succeeding in figuring out how to do it. Page 32 in the 887 spec talks about PIE1. Page 70 talks about T1CON. I do not know where to look for an example.

Is there a collection of PBP and ASM code samples? If so, where?

Ken

ScaleRobotics
- 19th November 2010, 15:17
Hey Ken,

I know a lot of people prefer on interrupt type. But my vote for easy interrupt is to use Darrels instant interrupts (and I think an equally large number of people like them as well). Here is a simple example of a blinky interrupt using his include files. The pages on this site have a lot of information about the different kinds of interrupts you can do. Your chip needs to use DT_INTS-14. And of course DT_INTS-18 is for PIC18 devices.

http://darreltaylor.com/DT_INTS-14/blinky.html

cncmachineguy
- 19th November 2010, 17:55
I don't think you want on interupt, just my opinion from reading the manual. I think you want to figure out DT int. Seems to be true int without Dealing with ASM.

mackrackit
- 19th November 2010, 20:11
I agree that DT's interrupts or ASM's are the way to go. I gave the ON INTERRUPT code above as an example to get started. Ken will still need to know how pre-scalers and such work no matter what.

Ken seems to want to know the nuts and bolts of things. In my opinion getting a simple code to work with ON INTERRUPTS is a crawl/walk thingy.

I am not real clear on how the motor driver works. I understand it as PWM greater than 127 turns one way and less than 127 turns the other way??

I just drove home trying to simulate Ken's car. Pulsed the same degrees left or right, more pulses left or right for turns but always the same, say 5 degrees off center, and after each pulse returned to center.

What about a two chip solution. The main chip will do nothing more than
center, pulse left, center, pulse right, center...

Second chip deals with the sonar. If a correction needs made a given pin is toggled.

The main chip is using an interrupt on change and completely interrupt driven. The main chip can deal with the pulse left, center, pulse right while the other chip is busy with the next calculation.

Just a half baked thought.

Kenjones1935
- 19th November 2010, 20:28
Right now I want an interrupt every 5 millisec. With a 1megahz clock and a 65356 counter, every 5 millisec is every 5000 ticks of that clock. cncmachineguy suggests that I generate an interrupt each time the clock gets down to 60356 by pre-setting the TIMER1 counter.

I understand that, but have not the faintest notion how to accomplish it. I have gone to Darrel Taylor's site. It is well written, but I do not see how it helps me.

Please help me get an interrupt every 5 millisec. Then I can try to figure out what code is needed to control the little car.

Ken

cncmachineguy
- 20th November 2010, 00:12
I just drove home trying to simulate Ken's car. Pulsed the same degrees left or right, more pulses left or right for turns but always the same, say 5 degrees off center, and after each pulse returned to center.


How'd that work out for you? :)

@Ken, Clearly there is some learning/teaching to be done here. What would you like to start with? DT_INTS or pre scaling and such?

For DT_INTS, I am gonna grab a copy and look/learn it myself. I will prolly jump on the learning side with you when you are ready to go through it. There are plenty here that will be able to answer any/all of our specific questions.

As for the pre scaler, I will go grab a copy of your datasheet. I agree with Dave, this is something you should understand even if you don't need it just yet.

BTW, PIE1 is Peripheral Interupt Enable 1. Without looking (yet) at the datasheet, I am guessing that is the enable for timer 1. In ASM, to use interupts, you must do 2 things. GIE must be set (Global Interupt Enable) this allows any interupt to do its thing. then you must set each interupt enable you want to use such as PIE1. Now with DT_INTS, I think that may be taken care of as part of the include, but I am not sure just yet.

mackrackit
- 20th November 2010, 03:01
How'd that work out for you?
Worked well until I pulled up to the checkpoint doing it. Thought they were going to take me to secondary...

Ken,
Here is code using DT's INTs giving an interrupt at 200 Hz.
All I did was tweak Darrel's blinky example.


<font color="#008000"><b><i>'FL PIC16F887
'16F887 DT INT RUPT
'44 PIN DEMO BOARD

'REMOVE THIS LINE IF NOT SETTING THE CONFIGS IN CODE SPACE
</i></b>@ __config _CONFIG1, _INTRC_OSC_NOCLKOUT &amp; _WDT_ON &amp; _MCLRE_OFF &amp; _LVP_OFF &amp; _CP_OFF
</font><font color="#0000FF"><b>OSCCON </b></font>= <font color="#800000"><b>%01100000 </b></font><font color="#008000"><b><i>'4 Mhz
</i></b></font><font color="#FF0000"><b>DEFINE </b></font><font color="#0000FF"><b>OSC </b></font><font color="#800000"><b>4

</b></font><font color="#0000FF"><b>LED1 </b></font><font color="#FF0000"><b>VAR </b></font><font color="#0000FF"><b>PORTD</b></font>.<font color="#800000"><b>4
</b></font><font color="#0000FF"><b>wsave </b></font><font color="#FF0000"><b>VAR BYTE </b></font><font color="#800000"><b>$70 </b></font><font color="#0000FF"><b>SYSTEM
</b></font><font color="#FF0000"><b>INCLUDE </b></font><b><i>&quot;DT_INTS-14.bas&quot; </i></b><font color="#008000"><b><i>' Base Interrupt System
</i></b></font><font color="#FF0000"><b>INCLUDE </b></font><b><i>&quot;ReEnterPBP.bas&quot; </i></b><font color="#008000"><b><i>' Include if using PBP interrupts

</i></b></font><font color="#FF0000"><b>ASM
</b></font><font color="#008000">INT_LIST macro <b><i>; IntSource, Label, Type, ResetFlag?
</i></b>INT_Handler TMR1_INT, _ToggleLED1, PBP, yes
endm
INT_CREATE <b><i>; Creates the interrupt processor
</i></b></font><font color="#FF0000"><b>ENDASM
</b></font><font color="#008000"><b><i>'5.0 mSec OR 200 Hz INTERRUPTS
</i></b></font><font color="#0000FF"><b>T1CON </b></font>= <font color="#800000"><b>%00000001 </b></font><font color="#008000"><b><i>'Prescaler = 1:1, TMR1ON
'PRELOAD 60543
</i></b></font><font color="#0000FF"><b>PreLoad </b></font><font color="#FF0000"><b>VAR WORD
</b></font><font color="#0000FF"><b>PreLoad </b></font>= <font color="#800000"><b>60543
</b></font><font color="#0000FF"><b>TMR1L </b></font>= <font color="#0000FF"><b>PreLoad</b></font>.<font color="#0000FF"><b>LowByte
TMR1H </b></font>= <font color="#0000FF"><b>PreLoad</b></font>.<font color="#0000FF"><b>HighByte
</b></font><font color="#008000">@ INT_ENABLE TMR1_INT <b><i>; enable Timer 1 interrupts

</i></b></font><font color="#0000FF"><b>Main</b></font>: <font color="#008000"><b><i>'DO WHATEVER YOU WANT HERE
</i></b></font><font color="#FF0000"><b>PAUSE </b></font><font color="#800000"><b>1000
</b></font><font color="#FF0000"><b>HIGH </b></font><font color="#0000FF"><b>PORTD</b></font>.<font color="#800000"><b>7
</b></font><font color="#FF0000"><b>PAUSE </b></font><font color="#800000"><b>1000
</b></font><font color="#FF0000"><b>LOW </b></font><font color="#0000FF"><b>PORTD</b></font>.<font color="#800000"><b>7
</b></font><font color="#FF0000"><b>GOTO </b></font><font color="#0000FF"><b>Main

</b></font><font color="#008000"><b><i>'---[TMR1 - interrupt handler]--------------------------------------------------
</i></b></font><font color="#0000FF"><b>ToggleLED1</b></font>:
<font color="#FF0000"><b>TOGGLE </b></font><font color="#0000FF"><b>LED1
</b></font><font color="#FF0000"><b>TOGGLE </b></font><font color="#0000FF"><b>PORTC</b></font>.<font color="#800000"><b>6 </b></font><font color="#008000"><b><i>'CONNECTED TO METER
</i></b></font><font color="#0000FF"><b>TMR1L </b></font>= <font color="#0000FF"><b>PreLoad</b></font>.<font color="#0000FF"><b>LowByte </b></font><font color="#008000"><b><i>' Load the timer with preload value.
</i></b></font><font color="#0000FF"><b>TMR1H </b></font>= <font color="#0000FF"><b>PreLoad</b></font>.<font color="#0000FF"><b>HighByte
</b></font><font color="#008000">@ INT_RETURN
</font>

cncmachineguy
- 20th November 2010, 03:21
Hi Ken, Just looked over section 6. I always think about the prescaler like this:

With no prescaler, timer increments as I posted earlier, Every 4 counts of the ocs will inc the timer by 1. If you have prescale set to 2, timer will inc every 8 counts, or half as fast. set to 4 it will inc every 16 counts or 1/4 speed, and set to 8, timer will inc every 32 counts or 1/8 speed. does this make sense?

So in summary, the prescaler is really a clock divider for the timer.

cncmachineguy
- 20th November 2010, 03:32
Quick question, how did you determine the preload value? I mean to say, I understand what it represents, just how did you determine the offset?

mackrackit
- 20th November 2010, 03:51
I cheated :p
http://www.picbasic.co.uk/forum/content.php?r=159-New-PIC-Utility.-PICMultiCalc

Kenjones1935
- 20th November 2010, 23:20
Not much luck reading DT_INTS-14. I do not understand ASM and all the macros that have been written.

Soooo I installed the two blinky programs and they both looked correct. I activated the LOGIC TOOL from PICKIT2 and looked carefully at the 20millisec square wave. Close enough for government work. Next I changed the

TOGGLE PORTC.6 'CONNECTED TO METER command to


PWM PORTD.7, 127, 1
and hooked up Channel 2 of the LOGIC TOOL to PORTD.7.

I expected to see a single pulse every 20millisec. I even hoped that the pulse would be 1.5millisec long.

I see many pulses seemingly not related to the edges of the interrupt driven 50Hz square wave. I would show you all a picture, but my FastStone Capture is screwed up.

Is there any PWM-like command that makes one pulse ranging from 1millisec to 2millisec in 256 gradations?

Ken

mackrackit
- 20th November 2010, 23:27
carefully at the 20millisec square wave
That is odd, I must have something off...


Is there any PWM-like command that makes one pulse ranging from 1millisec to 2millisec in 256 gradations?
The PULSOUT command might do the trick?

Kenjones1935
- 21st November 2010, 02:51
Here is what my LOGIC TOOL displays. The only change in the code is this substitution of a PWM command.


ToggleLED1:
TOGGLE LED1
PWM PORTD.7,127,1
TMR1L = PreLoad.LowByte ' Load the timer with preload value.
TMR1H = PreLoad.HighByte
@ INT_RETURN
4961

Kenjones1935
- 21st November 2010, 03:37
I do not understand this result. The gist is that the pulse generating command seems to influence
the interrupt frequency. Here is exactly our same code with a PULSOUT PORTD.7, 50 inside the
interrupt routine.



OSCCON = %01100000 '4 Mhz
DEFINE OSC 4

LED1 VAR PORTD.4
wsave VAR BYTE $70 SYSTEM
INCLUDE "DT_INTS-14.bas" ' Base Interrupt System
INCLUDE "ReEnterPBP.bas" ' Include if using PBP interrupts

ASM
INT_LIST macro ; IntSource, Label, Type, ResetFlag?
INT_Handler TMR1_INT, _ToggleLED1, PBP, yes
endm
INT_CREATE ; Creates the interrupt processor
ENDASM
'5.0 mSec OR 200 Hz INTERRUPTS
T1CON = %00000001 'Prescaler = 1:1, TMR1ON
'PRELOAD 60543
PreLoad VAR WORD
PreLoad = 60543
TMR1L = PreLoad.LowByte
TMR1H = PreLoad.HighByte
@ INT_ENABLE TMR1_INT ; enable Timer 1 interrupts

Main: 'DO WHATEVER YOU WANT HERE
' PAUSE 1000
' HIGH PORTD.7
' PAUSE 1000
' LOW PORTD.7
GOTO Main

'---[TMR1 - interrupt handler]--------------------------------------------------
ToggleLED1:
TOGGLE LED1
pulsout PORTD.7,50
' PWM PORTD.7,127,1
' TOGGLE PORTC.6 'CONNECTED TO METER
TMR1L = PreLoad.LowByte ' Load the timer with preload value.
TMR1H = PreLoad.HighByte
@ INT_RETURN

And here's the LOGIC TOOL picture.

4962

mackrackit
- 21st November 2010, 09:53
Looks like the PULSOUT is taking longer than the interrupt. And of course I do not have the interrupt timed correctly.
Hopefully someone will straighten me out on the math.

cncmachineguy
- 21st November 2010, 09:53
According to the manual, each "PWM cycle" takes about 5ms with a 4Mhz clock. My guess is the first example has the interupt routine taking longer than the time between interupts. And you are prolly getting lucky to ever leave the handler at all!

The second example using pulseout, looks much better. Hard to count the lines, is it the correct timing?

Now remember, you don't want the pulseout in the interupt handler.

Kenjones1935
- 21st November 2010, 11:35
The correct picture is this one. PULSOUT is in the interrupt handler only after the RESET TIMER action. Why is this bad?

4964

cncmachineguy
- 21st November 2010, 12:17
The general rule is to get in and out of an interupt as fast as possible. But in your case, the problem is a bit different. the pulse for the servo's should be every 20 msec. you have an interupt every 5 msec. so you are updating the servo 4 times as fast as you want to.

ScaleRobotics
- 21st November 2010, 13:49
Great job Ken. What you are doing is the best way to learn about the interrupts. You have to play with them. That is a great start.

I believe both pulsin and pulsout are blocking commands. While they run, nothing else can happen on your chip. Once they are finished, sure, things resume and the program takes over. For a single servo, this is fine. But once you start throwing in sonar, multiple servos, other things you have thought of, and some you haven't thought of yet ... then you start to run out of time to do all these things using blocking commands. Especially if you want to go 20 mph.

As it stands, 20mph is half a foot for each 20ms (that is every chance you get to make an R/C correction). For your sonar, it takes a bit over 20ms, so if that is the only input, the best your chip can do is determine a correction every other 20 ms, or every foot.

In fact, just listening to the echo pulse on your sonar takes up to 25 ms, so that alone screws up everything if we use blocking commands like pulsin. (and double the screwed if you are listening to two of these!)

So, in the long run I think it is best to use interrupts for listening to your sonars, as well as outputting to your servo's. I can't remember how you are switching your transmitter for R/C control vs pic control, but that too might as well go on interrupts.

If you do, you have all kinds of time. You can be listening for two sonars at the same time, chewing on some math to determine the amount of turn, etc. If you want speed, it is most definitely the way to go.

That said, exactly what you are currently doing to learn is what I would recommend. Use the commands you know with interrupts to make things happen, and see how they work, and how to adjust them. Later on, when you feel comfortable with them, try adding in another interrupt timer to control a servo pulse.

cncmachineguy
- 21st November 2010, 14:03
Hi Walter, I love what you are saying about using int instead of pulsein/out. I am having trouble visualizing how to do that.

In my head, something has to be the overall clock, thats where my suggestion of 5msec came from. when I think about what you are saying, all I seem to be able to see is all these events started waiting for an int to make them stop. so I see like 6 different timers going all at once.

Or maybe you have 1 timer going for the 20ms, then do everything else sequencially using a different timer.

EDIT: The slow sonars are gonna definitly limit the top speed! Maybe as an upgrade once it works slowly, infra red emitters and detectors. This way they could also be used at the same time by sending different signals on each.

ScaleRobotics
- 21st November 2010, 14:22
That's a great question Bert. Well, you being an asm guy will probably get a few laughs at my first real attempt at using more than 20 lines of asm in my program. But I will show you anyway. This uses Timer1 for PWM measurement (read servo channels in). Basically, Timer1 runs non-stop, and when a state change interrupt is detected, the timer value is read. The start timer value is subtracted from the stop timer value to get the pulse width. This is done for all channels. After all channels are read, it is time to output pulses to the servos. So I do not have a 20 ms timer, it cheats and uses the R/C receiver as the 20ms timer. If all channels have been read, it must be 20 ms. The second interrupt is timer0. That is used for pulse duration on the output. I made the pulse base 1ms, then the timer gets set for a second interrupt to complete the pulse.

Here is an example of reading 5 R/C channels, and outputting 4 R/C channels using two timers: http://www.scalerobotics.com/PWMpassthrough.html

Something like that could be used. And in addition to detecting servo pulse in, and interrupt on change could time a pulse from two sonars at the same time. This could also read timer1 start and end times, so no additional timers would be needed. If you did not want to use the R/C receiver as the 20 ms timer, then timer2 could be used. But that is the last timer on this chip. But then, you can still throw more on those two other timers, if you wish.

cncmachineguy
- 21st November 2010, 15:09
Walter I never find things to laugh about in code that works! Besides, 20 lines of asm isn't really much. Thats one of the reasons I wanted to convert to a high level language. Fewer lines to type :)

Ken is worried about firing both sonars at the same time cuz he may not know who the source is when it comes back.

ScaleRobotics
- 21st November 2010, 15:25
Ken is worried about firing both sonars at the same time cuz he may not know who the source is when it comes back.

Ken was thinking smarter than I. Good point. Maybe keep your sonar for front view, and for side view something like this: http://www.acroname.com/robotics/parts/gp2y0a21yk_e.pdf . Or use infra sensors for both, since you can get updates every 20 ms to keep up with the fastest that you can change your servos. Besides, they are cheaper than sonar! You do need to pick your distance range though. The one I gave a link to was 4 inches to 30 inches, which seemed ok for following a wall. If its 30 inches or more, get closer....

Kenjones1935
- 21st November 2010, 15:28
Yes, "blocking commands" is exactly the word. I figured that out while lying in bed with the LOGIC TOOL image in my head. I could see that the length of the pulse was being added to the interrupt time. I could not find any information on that in any of my documents. Please tell me where in which .INC file is the ASM code which is activated by PULSOUT. Without access to those details, PBP is just guess work.

My plan is to insert counters into the interrupt service routine. Every four interrupts (20millisec) do a PULSOUT. Every 25 interrupts, TRIGGER one SONAR or the other alternatively. My TRIGGER is built of HIGH and LOW commands totaling 10 microseconds (or so). These are not blocking.

I'll give this a try and see how the car reacts (if at all.....)

Thanks again for the support.

Ken

ScaleRobotics
- 21st November 2010, 15:50
Please tell me where in which .INC file is the ASM code which is activated by PULSOUT. Without access to those details, PBP is just guess work.

I would approach it a different way, and avoid that pain. Especially since interrupts may grow on you, and you may get rid of your pulsin/out someday :)! Say you want an interrupt every 20 ms and have a single servo to control, but you want to use pulsout since you are still learning interrupts. Since we can be a little off on our 20 ms, as Bert mentioned, the easy way is to say the average servo pulse is 1.5ms, so I need to interrupt every 18.5 seconds. If you add in the time of your pulsout, it will be very close to 20 ms, and your servo will be happy and grateful.

ScaleRobotics
- 21st November 2010, 16:21
My plan is to insert counters into the interrupt service routine. Every four interrupts (20millisec) do a PULSOUT. Every 25 interrupts, TRIGGER one SONAR or the other alternatively. My TRIGGER is built of HIGH and LOW commands totaling 10 microseconds (or so). These are not blocking.

If that plan is just for testing, it sounds like a great plan. But if you plan to use it while doing 20 mph, you will be doing a "ping" every 3.66 feet, or 8 times per second. If your reflexes are quick, you might be able to blink your eyes quickly at about 8 times per second. While your R/C car is doing 20 mph around a turn, try blinking your eyes as fast as you can, while steering your R/C car. I think your results might be similar to the ones we saw in the video.

cncmachineguy
- 21st November 2010, 16:28
see, this is one of the reasons I love this stuff. To do what Walter describes, with the same resources (1 interupt and pulsout), I would set my timer for 20 ms. My int handler would set a flag, and I would get out. Then in my Main, if the flag is set, hit my pulseout routine and clear the flag. This way I would get a new pulse every 20 ms on the dot. But mostly cuz I just always want to get out of the handler. I seem to feel like by name "Interupt" I was busy doing something before I went there. Maybe it was important and I need to get back to it.

As for PBP being guess work, I don't think thats the case. Pulseout/in serout/in and the rest of them, take exactly as long as you think. if you PULSEOUT for 1 ms, thats how long it will take.

cncmachineguy
- 21st November 2010, 20:04
Walter, I like your idea of the 18.5 ms plus servo out to make up the 20ms loop. I need just that for my project. I will want to use 1 timer to control the loop and the pulse, so that seems the best idea to me.

Kenjones1935
- 22nd November 2010, 03:58
"Verification of Program Memory failed at address 0x00000000"

I tried some old code that I KNOW loaded. Not today.

I swapped out the PIC. That was not the problem. I reseated all the patch wires. That made no difference.

I restarted the PICKIT2 programmer. That did not help.

I tried with a PICKIT2 board - the one on which I ran the blinkys - no problem. It liked to load and blink.

Where do I start?

Ken

Kenjones1935
- 22nd November 2010, 04:24
It was a wire I had added to give the LOGIC TOOL more information. I do not understand why the PICKIT objected. But all is well.

The interrupt driven system sort of works. We'll see more tomorrow.

Thanks again for your help and support.

Ken

Kenjones1935
- 22nd November 2010, 16:16
I've got the system working interrupt driven. I do not have proportional controls implemented - yet.

On the bench the car seems as responsive as before. We'll see when I take it to the gym.

One thing I have not figured. How, now, to I disable interrupts when the radio transmitter has been
turned ON? At the very end of this code pack is my old WHILE loop that worked - in the day.


symbol trigright = PORTB.0 ' Define output pin for Trigger pulse
symbol trigfront = PORTB.1 ' Define output pin for Trigger pulse
symbol trigleft = PORTB.3 ' Define output pin for TRigger pulse
symbol echoright = PORTC.6 ' Define input pin for Echo pulse
symbol echofront = PORTC.5 ' Define input pin for Echo pulse
symbol echoleft = PORTC.7 ' Define input pin for Echo pulse
SYMBOL channel3 = PORTC.4 ' Define input pin for Channel 3 PWM
' PORTC.0 'High is R/C. Low is PIC control
TRISC = %11110000
DATA $C0,$0C 'his version's checksum goes here.
define ADC_BITS 8
TRISA.0 = 1 'PORTA.0 as analog input for POT
ANSEL.0 = 1
ADCON1 = %00000000 'left justified
' We use low eight bits. 0 -> 255.
ADCON0 = %01000001 'divide 4Mhz clock by 8.

'------------
OSCCON = %01100000 '4 Mhz
DEFINE OSC 4

LED1 VAR PORTD.4
wsave VAR BYTE $70 SYSTEM
INCLUDE "DT_INTS-14.bas" ' Base Interrupt System
INCLUDE "ReEnterPBP.bas" ' Include if using PBP interrupts

ASM
INT_LIST macro ; IntSource, Label, Type, ResetFlag?
INT_Handler TMR1_INT, _ToggleLED1, PBP, yes
endm
INT_CREATE ; Creates the interrupt processor
ENDASM

'------------

'5.0 mSec OR 200 Hz INTERRUPTS
T1CON = %00000001 'Prescaler = 1:1, TMR1ON
'PRELOAD 60543
PreLoad VAR WORD
PreLoad = 60543
TMR1L = PreLoad.LowByte
TMR1H = PreLoad.HighByte
'@ INT_ENABLE TMR1_INT ; enable Timer 1 interrupts

'------------
WHEELS VAR WORD
STEERING VAR WORD

'The following may be a big part of the wall hugging probllem
Potread var word
Forward var word ' was fixed 122. Now sweeps 7 steps. See Checkpot
HalfForward VAR WORD ' Potread/2 +x + 1. See Checkpot
Back VAR WORD 'See Checkpot
HalfBack VAR WORD 'See Checkpot
Brake con 100 'Only used just before Main.

Straight con 150 '?
Right CON 130 '?
HalfRight con 135 '?
QuarterRight CON 140 '?
Left con 170 '?
HalfLeft con 165 '?
QuarterLeft con 160 '?

'---------------------------
frontdanger var word
stopreversing var word
frontfree var word
desiredtrack var word
outertrack var word

'---------------------------

'some of the following are not used.
CNT VAR BYTE 'counts interrupts for TRIGGERS
cnt = 0
CNT2 var byte ' counts interrups for wheels and steering
CNT2 = 0
b0 VAR word
rangeright var word
rangeright = 100 'about 6 inches preset
rangefront var word
oldrangeright var word
oldrangefront var word
reversing VAR WORD
reversing = 0
switchtoPIC VAR WORD
switchtoPIC = 1
radiocontrol var word
radiocontrol = 0
steeringleft var word
steeringleft = 0
steeringright var word
steeringright = 0

'-------------------
Checkpot:
' I think Potread goes from 0 to 6.
adcin PORTA.0, Potread
Potread = Potread/37
Forward = 160+Potread
HalfForward = 155+(Potread/2) 'seems to work.
Back = 140-Potread
HalfBack = 145-(Potread/2)
'----------
frontdanger = 210 + Potread*55 '210-540, 14-36 inches
stopreversing = 180 + Potread*25 '180-330, 12-22 inches
frontfree = 700 + Potread*60 '700-1060, 48-70 inches
desiredtrack = 180 + Potread*20 '180-300, 12-20 inches
outertrack = 360 + Potread*15 '360-450, 24-30 inches

'----------
write 2, word Potread
write 4, word frontdanger
write 6, word stopreversing
write 8, word frontfree
write 10, WORD desiredtrack
write 12, word outertrack

'-------------------
@ INT_ENABLE TMR1_INT ; enable Timer 1 interrupts

'-------------------
low PORTC.0
'hpwm 1,Straight,50
STEERING = Straight
'hpwm 2,Brake,50
WHEELS = Brake
'pause 4000 'Wait so I can put the car down and get out of the way.
'-------------------

main:

CheckIfInDanger:
if rangefront < frontdanger then
STEERING = Straight
WHEELS = back
reversing = 1
goto reverseoutoftrouble
' loop till this is secured
endif
'-------------------
tryleftturn:
if rangefront < frontfree then
'something ahead - turn hard left.
STEERING = left
WHEELS = halfforward
steeringleft = 1
goto main 'loop till this is secured
endif

'-------------------
goingforward:
STEERING = straight
WHEELS = forward

'-------------------
keepgoingforward: '----Compare to right wall
if rangeright > outertrack then
STEERING = quarterright
endif

if rangeright < desiredtrack and oldrangeright < rangeright then
STEERING = STRAIGHT
endif

if rangeright > desiredtrack and oldrangeright > rangeright then
STEERING = STRAIGHT
endif

if rangeright > desiredtrack and oldrangeright < rangeright then
STEERING = QUARTERRIGHT
endif

if rangeright < desiredtrack and oldrangeright >= rangeright then
STEERING = QUARTERLEFT
endif

goto main

'-------------------------
reverseoutoftrouble:
while rangefront < stopreversing
STEERING = RIGHT
WHEELS = RIGHT
wend

if rangeright > outertrack or rangeright < desiredtrack then
STEERING = LEFT
steeringleft = 1
WHEELS = HALFFORWARD
endif
goto main

'***********INTERRUPT HANDLER************
ToggleLED1:
TMR1L = PreLoad.LowByte ' Load the timer with preload value.
TMR1H = PreLoad.HighByte
TOGGLE LED1

'------------
' Trigger SONAR alternatively every 25 interrupts
if CNT=25 then
pulsr:
oldrangeright = rangeright
' produce 10uS trigger pulse (must be minimum of 10uS)
low trigright
HIGH trigright
high trigright
high trigright
LOW trigright
'zero could be legal below
pulsin echoright,1,rangeright 'measures the range in 10uS steps
endif

'-------------
if CNT=50 then
pulsf:
oldrangefront = rangefront
low trigfront
hIGH trigfront
high trigfront
high trigfront
LOW trigfront
pulsin echofront,1,rangefront ' measures the range in 10uS steps
CNT=0
endif
CNT=CNT+1

'--------------
if cnt2=4 then
' PWM pulses are between 1 and 2 millisec.
low PORTC.1
low PORTC.2
pulsout PORTC.1,WHEELS
PULSOUT PORTC.2,STEERING
CNT2=0
endif
CNT2=CNT2+1

@ INT_RETURN
checkchannel3:
'works with four AA batteries pack. Radio receiver puts pulses
'on this line whenever the transmitter is turned ON.
switchtoPIC = 2
while switchtoPIC >= 2
count channel3,65,switchtoPIC
high portc.0
wend
low portc.0

end

cncmachineguy
- 22nd November 2010, 19:15
@ INT_ENABLE TMR1_INT ; enable Timer 1 interrupts


that line turns the interupt on, or enables it. there must be a simular line like INT_DISABLE maybe to turn it off.
turn it off when the while loop is true, or when under Tx control. then turn it back on when Tx control is over.

Kenjones1935
- 22nd November 2010, 23:10
For some reason disabling interrupt during the WHILE loop did not work. I could have done
something stupid.

What I want to know is where is the list of "blocking" commands. I do not see such a list in
my PBP book. For example, is COUNT a blocker?

Here is what I coded immediately after main:
main:

'-------------------

checkchannel3:
'worked with four AA batteries pack. Radio receiver puts pulses
'on this line whenever the transmitter is turned ON.
switchtoPIC = 2
while switchtoPIC >= 2
@ INT_DISABLE TMR1_INT
count channel3,65,switchtoPIC
high portc.0
wend
low portc.0
@ INT_ENABLE TMR1_INT

Ken

ScaleRobotics
- 23rd November 2010, 03:08
Ken, can you give us a bigger snippet?

Kenjones1935
- 23rd November 2010, 22:40
I took my interrupt driven car to the gym this morning. It behaved about the same as my old HPWM design. When going slowly it just barely made the left turns at the corners. It did seem to go straight with less wiggle, but it still hit the wall occasionally.

It appears that the problem is reaction time. My delving into an interrupt driven system was motivated by the guess that randomly (in time) changing the HPWM command might be confusing the electronic speed control. On this account I detect little difference.

Another reason for regularly timed SONAR triggers was to take advantage of PID control. I have not coded that experiment. I am not convinced quicker reaction time will result.

I partially solved the TOGGLE problem by inserting the following code right after 'main:'. This system does not toggle control between PIC and RC, but it does stop (Brake) the car when the radio transmitter is turned ON. It is not a nice picture - a 75 year old man running around a gymnasium trying to tackle an out-of-control RC car.

The code samples channel3. This is the steering PWM signal from the car's radio receiver. There are pulses on that line as soon as the transmitter is activated.

main:
switchtoPIC = 2
WHILE switchtoPIC >= 2
COUNT channel3, 65, switchtoPIC
WHEELS = Brake
WEND

I am not sure what to do now. The reaction time seems quick enough on the bench.

Kenjones1935
- 24th November 2010, 00:47
In order to make sense of interrupt driven controls I need to know which PBP commands are 'blocking'. Why? During the blocking time no PWM pulses and no SONAR triggers are being emitted.

Ken

Kenjones1935
- 24th November 2010, 02:57
Back a couple weeks one of you mentioned using infrared distance detector instead of a sonar detector. How do I find that posting? What was he product's name? How does it work? Or am I mistaken.

Ken

ScaleRobotics
- 24th November 2010, 04:47
Ken, the one I suggested earlier http://www.acroname.com/robotics/parts/gp2y0a21yk_e.pdf... well, I just read the timing chart on page 4, and believe it or not, this infra red sensor is slower than your sonar! But, the good part is, you wouldn't have to wait for one to finish, before sensing the other. It would be nice to find a faster response sensor, if possible though, to allow your car to measure under 20 ms (at least for the side).

Here's a little bit about how they work http://www.societyofrobots.com/robotforum/index.php?topic=7991.0

ScaleRobotics
- 24th November 2010, 06:48
In order to make sense of interrupt driven controls I need to know which PBP commands are 'blocking'. Why? During the blocking time no PWM pulses and no SONAR triggers are being emitted.


Interrupts are the way around blocking commands. With interrupts, you can be listening for 4 separate pulses in, while pulsing 4 separate pulses out, while listening for the sonar ping, and blinking a few led's, etc, etc. With PicBasic commands alone, you are still stuck at pulsin, listening for a single pin for x duration. Don't get me wrong, blocking sounds so bad, but what it really does, is give the user a simple way do some complex things, with a single line of code. And without having to read about 50 extra pages of the data sheet. This is one of the best features of PicBasic. But there is a time for interrupts. Pulsin, Pulsout, PWM, serin, serout, freqout, count, debug, debugout are a few blocking commands.

That said, they will not block an interrupt. An interrupt, does what it does best. It butts in an interrupts, gets out, and then whatever PicBasic command it was in the middle of completes.

Ioannis
- 24th November 2010, 07:49
Up to this moment I have not seen any specifications of the cars.

What speed they reach, how fast thay accelerate and how fast do they stop.

If youhave this figures then you may do the calculations about reaction time and maximum speed to reach in order to hit the brakes in time, before crashing on the walls.

Ioannis

ScaleRobotics
- 24th November 2010, 16:30
Looking back at one of the examples you gave of this idea (from kind of the beginning), Wall Racers used no interrupts. It was all done using basic statements, and blocking commands. These cars seem to go a bit slower than yours though, if I were to guestimate. Is the accuracy and speed they have in this video what you are aiming for? I think I saw them hit a wall here and there ... maybe. I am guessing around 4 to 5mph in the video?


http://vimeo.com/1162192

Here is the code they used in PicAxe Basic.




' WALLRACERS By Frits Lyneborg
' Right turns on the track must be gentle (this code does not skid/slide on them), left can be hard (skid/slide is build in)

' <"left"> opposite just <left> in the remarks means that wheels are turning left, but direction is backwards, so "left" is actually moving right

symbol trigright = 0 ‘ Define output pin for Trigger pulse
symbol trigfront = 1 ‘ Define output pin for Trigger pulse

symbol echoright = 7 ‘ Define input pin for Echo pulse
symbol echofront = 6 ‘ Define input pin for Echo pulse
symbol rangeright = w1 ‘ 16 bit word variable for range
symbol rangefront = w2 ‘ 16 bit word variable for range
symbol oldrangeright = w3 ‘ 16 bit word variable for range
symbol differencerangeright = w4 ‘ used to calculate how hard a turn is
symbol frontfreetostopreverse = w5

symbol turnon = 7 ' the relay that if on makes the car turn to one side
symbol steerto = 6 ' the relay that if on turning is on, then decides the direction
symbol stopon = 5 ' the relay that if on makes the car stop
symbol forrev = 4 ' the relay that if on and is not on stop makes the car reverse


symbol frontdanger = 200 ' At what point should we realize we are getting too close? (note that breaking takes a lot, so this should be much higher than the real distance)
symbol frontfreetostopreversesetup = 201' must be higher than "frontdanger" - higher value means more backing out after close encounters
symbol frontfree = 350' set higher to turn earlier when something is in front, and get less skid-turning, but more likeliness to miss sharp right turns

symbol desiredtrack = 100
'symbol innertrack = 50
symbol outertrack = 150

high stopon
wait 5
low stopon

'''''''''''

main:
oldrangeright = rangeright
gosub puls
gosub skidandreverse
if rangefront < frontfree then 'turn left as there is something ahead in front
high turnon low steerto
goto main 'this is second priority above all loop till this is secured
end if


'' Normal drive to the right - we are too far away from the lane, so turn. This code contains no right-slide-turn for cool long right turns without slides to give more of a race-feeling oposed to zig-zag and robot-behaviour, so space must on thr track be higher than turning-radius in front of right turns - or the car vill turn left and miss the right turn.
if rangeright > outertrack then 'turn right as we are too far away
high turnon high steerto
end if



' Now we know that there is nothing closer than (frontdanger and) frontfree - and we are on track - so let's keep on track

'***
' First check if we are on the right path and have a positive development.
' If so, then keep us there by straightening up wheels that might be turned

if rangeright < desiredtrack and oldrangeright < rangeright then
low turnon low steerto ' drive straight forward as we are on the wrong side of desired track, but we are moving the right direction
end if

if rangeright > desiredtrack and oldrangeright > rangeright then
low turnon low steerto ' drive straight forward as we are on the wrong side of desired track, but we are moving the right direction
end if

'***
' Then see if we are moving away from the good path and do something about it if so.

if rangeright > desiredtrack and oldrangeright < rangeright then
high turnon high steerto 'turn right as we are in the outer lane and getting away
end if

if rangeright < desiredtrack and oldrangeright > rangeright then
high turnon low steerto 'turn left as we are in the inner lane and getting closer
end if

goto main

'***************************************

yankright:' there was an empty space to the right. Skid right to be sure we are turning if it is a turn in the track


'''''''''' Skidsecure start
high turnon high steerto 'turn right
pause 25' wait short for the car to give a small yank to the left before reversing.. all to start a skid turn to the right side
'''''''''' Skidsecure end

high forrev 'set in reverse gear


Skidright:
b0 = 0

do
gosub puls
b0 = b0 +1
loop while rangefront > frontfreetostopreverse and rangeright > outertrack and b0 < 20

'dildo:
'high stopon goto dildo

low forrev 'set in forward gear
pause 300

return


'***************************************



'***************************************

reverseoutoftrouble:

'''''''''' Skidsecure start
high turnon low steerto 'turn left
pause 25' wait short for the car to give a small yank to the left before reversing.. all to start a skid turn to the right side
'''''''''' Skidsecure end

high forrev 'set in reverse gear

rev:
frontfreetostopreverse = frontfreetostopreversesetup

keepreversing:
frontfreetostopreverse = frontfreetostopreverse - 3' making sure we are not backing and reversing and going nowhere, as we have a wall behind us

if frontfreetostopreverse < 50 then
gosub stuckerror
end if

gosub puls
if rangefront < frontfreetostopreversesetup then

if rangeright < desiredtrack and oldrangeright < rangeright and rangefront > frontdanger then
low turnon low steerto ' drive ahead as we are on the wrong side, but we are moving the right direction and we are not too close
end if

if rangeright > desiredtrack and oldrangeright > rangeright and rangefront > frontdanger then
low turnon low steerto ' drive ahead as we are on the wrong side, but we are moving the right direction and we are not too close
end if


if rangeright > desiredtrack and oldrangeright < rangeright and rangefront > frontdanger then
high turnon low steerto 'turn left (reversed) as we are in the inner lane and getting closer
end if

if rangeright < desiredtrack and oldrangeright > rangeright then
high turnon high steerto 'turn right (reversed) as we are in the outer lane and getting away
end if

goto keepreversing
end if

high turnon low steerto 'turn "left"
low forrev 'set in forward gear

return


'*************

skidandreverse:
if rangefront < frontdanger then ' too close, reverse out of trouble!
gosub reverseoutoftrouble
goto main ' this is first priority above all - loop till this is secured
end if
return

'*************

puls:
pulsout trigright,2 ‘ produce 20uS trigger pulse (must be minimum of 10uS)
pulsin echoright,1,rangeright ‘ measures the range in 10uS steps
pulsf:
pulsout trigfront,2 ‘ produce 20uS trigger pulse (must be minimum of 10uS)
pulsin echofront,1,rangefront ‘ measures the range in 10uS steps
pause 10 ‘ recharge period after ranging completes
return


stuckerror:
high stopon
low forrev
low steerto
low turnon
dadaa:
goto dadaa

Kenjones1935
- 24th November 2010, 16:48
You are right about the specs on the RC cars. I do not know that they officially exist. My car weights exactly four pounds. Has good rubber tires with plenty of friction against the gymnasium floor. I have been told that it is good for at least twenty miles per hour, but I have no means to verify it. The car is a HPI-Racing 1/10 Scale, 4 wheel drive, Sprint model.

Regarding the blocking commands. All I want to know is which ones block TMR1 and hence TMR1 based interrupts? Judging from my LOGIC TOOL images PULSIN blocks. True?

Ken

ScaleRobotics
- 24th November 2010, 17:21
Regarding the blocking commands. All I want to know is which ones block TMR1 and hence TMR1 based interrupts? Judging from my LOGIC TOOL images PULSIN blocks. True?

I thought I read somewhere that most of the commands which involve time, like Pulsin, Pulsout, etc, use timer1. But I can't find anything documenting that. Maybe someone can correct this for me? I did a little testing, and if you put your 20 ms timer on Timer2, it will be unaffected by pulsout, and I expect pulsin as well. These blocking commands DO NOT block an interrupt. For instance, you can have a pause 10000 in your main, while an interrupt gives you a heartbeat LED indication every second. But they will interfere if they are trying to load the same timer with a value.

EDIT: Turns out I was way off base here. Here Darrel corrects me:



The only PicBasic command that uses a timer is HPWM, which uses Timer2.
No PBP commands use Timer1 unless you tell it to.

And all PBP commands are blocking (while they execute).
They might interface with harware peripherals that are doing other things at the same time, but the statements themselves are blocking.

As you pointed out though, they don't block interrupts.
And it's the commands that do software based timing that get disturbed by the interrupts.
PAUSE, PULSIN/OUT, RCTIME, SEROUT/IN(2) etc.
They stop keeping time while the interrupt code executes, so all that time gets lost.

When using interrupts, you should use Hardware Timers to do things like PAUSE or PULSIN, and the USART instead if SEROUT/IN(2).
And when not using interrupts, use the easier versions (PBP), or still use the hardware which are the NON-BLOCKED functions.

You can do PULSIN with the CCP module at the same time you're sending serial data to a PC without any interrupts.

Kenjones1935
- 24th November 2010, 17:34
You are correct. I got the whole idea from Frits. I have learned some since then.

1. His cars were 1/12 scale toy level cars. They are not fast by RC standards. They have only bang bang steering and wheel control. They are small. They do not have enough room for much electronics to be added. Frits removed the RC receiver. I tried the Frits thing on a 1/10. I was not successful. The 1/10 car is much faster than the 1/12 car. This video shows the difference.


http://www.youtube.com/watch?v=Emsf46WpctI

I have been asking for suggestions for a 'game' that can be played with the 1/10 Toy level cars. They are $50 each vs $200 for a model level car.
I thought up the 'swarm the teacher with the light bulb' game to be played with multiple light sensing diodes on the roofs of the cars. I have been diverted by this idea of interrupt driven model level control.

Thanks for everything.

KEn

cncmachineguy
- 24th November 2010, 19:51
Ken, Sorry, I'm not very good at thinking up games. Follow the light sounds like fun to me. I have a lot of things I want to comment about your current effort, but time won't let me right now. I will tonight. Let me say this though, I think you are on the right path.

I wonder if you can do some testing for us. I want to help you get better control over the car, but need some parameters.

1. How close can you get to a wall at top speed and still be able to execute a turn?
2. How close do you want to be to the right wall?
3. At what percentage of speed can you still make a hard left without the car skiding?
4. If the Tx is NOT on, will there be any pulse from the RX?

Maybe you can put some tape lines on the floor and film that section of the floor to capture speed and distance from the wall. Of course this will be under manual control, So we will also get to see your reflexes-lol

I for 1 believe you can get the car to go much faster and be WAY more accurate!!

Kenjones1935
- 24th November 2010, 20:13
My gymnasium has no electricity. Need bright sunny day to take video. Tomorrow is Thanksgiving and the following day is occupied by family stuff.

The model car does not skid. The toy car does.

In my older model level car, the receiver created no pulses on channel3 input when the transmitter was off. My newer model level car, somehow has noise on that line. The circuits are the same. I have not been able to figure out the difference.

I started trying to code my 1/10 toy car to do a skid turn then I realized that it's real problem is the subtle issue of staying parallel to the wall. I think you have a real good idea asking me to see whether I can control that car with its RC inside my gym.

Thanks for the encouragement. I have been bumping my head for a while.

Ken

Kenjones1935
- 24th November 2010, 20:28
I have built four cars.

Two 1/10 scale model level. My original and my new one. The new one is inherently much faster. They are both the same car from the same company.

Two toy level:
One 1/12 scale which is similar to Frits'.
One 1/10 scale which you saw in my video.

Maybe I should bring them all to the gym on a sunny day for a grand comparison.

Ken

cncmachineguy
- 24th November 2010, 21:03
What I am really trying to do is get some numbers together for things like : at half speed, must turn by XX inches or we will crash/skid. Also after watching your video again, the wall tracking appears to be a combination of 2 things. too much time between sensor readings, and too much turn (over driving)

'side note
My personal feeling is to get all the driving out of the int and in the main, but it might not matter. Just good coding. Imagine on your next project, when an int occurs, you could not tolerate a 4ms delay from what ever you were doing.
'end side note

Back on topic: so why not try increasing the sonar to every 50ms for each? This would more than double the resolution of your readings. Then we need to address more choices for how much to turn. A couple pages back you had asked if the math could be done digital. the answer is yes of course, just type more if statements. maybe instead of 2 stage steering, how bout 10% increments? fom 0-100%

something else picking at me is the timing. right now, every half sec, your int could take longer than 5ms. this is because of :2 servo updates could be 4 ms, plus at cnt=50*2 cnt2=4 so you have to ping sonar 2 also. Actually, come to think of it, sonar could last up to 30 ms!!!! so that is definantly too long for the 5 ms interupt.
sample int handler:


reload timer
cnt=cnt+1
cnt2=cnt2+1
flags=0
return

simular written in asm:


movlw _preload.lowbyte
movwf timer1L
movlw _preload.highbyte
movwf timer1H
inc _cnt
inc _cnt2
movlw 0
movwf _flags
return

I would have to check your datasheet again to make sure the inc's are correct and I'm not sure about using your PBP variables like that, but I think its correct.

I gave you the ASM equalviant so you could see what it is and if you want to use asm, you don't need to include PBP_include or whatever it is

Kenjones1935
- 26th November 2010, 03:59
Some time ago, I know not when, I purchased PIC MICROCONTROLLERS from MikroElektronika. Then I put it in a pile and forgot. It reappeared this morning. Looks like I have much of the ASM info I have been seeking.

My old HPWM system uses a TRIGGER: subroutine for SONAR triggers. The leds on the SONARs blink many times per second. They are too fast to count accurately. Each SONAR blinks at least 55 times in ten seconds. My non-mathematical guess is fast's enough if the steering servo and the wheel motor are reacting 'instantly'. Which they are not.

I think I have learned that there is no advantage keeping the PWM signal down to 50hz. All that is necessary is to calibrate the pulse widths as they appear in HPWM 2, xx, 50.

Kenjones1935
- 27th November 2010, 04:25
A number of your suggestions push me to work quantitatively. I have been 'eying' my distances - measuring with outstretched hand tip of thumb to tip of little finger = about ten inches.

I would have a better handle on the behavior of my robocar if the SONAR measurements were in decimal inches. Right now I have a system of translating the echo pulse size to inches that I derived empirically. It would make my life easier if when I do a READ of numbers I have stored in EEPROM Data they came out as digital. How with PBP do I do that?

cncmachineguy
- 27th November 2010, 11:49
Thats an easy one Ken :) sinec your result is measured in 10uS steps, according to the spec for your sonar, "If the pulse is measured in uS, then divide by 148 to get inches". So all you have to do is inchesright = rangeright/148. And inchesfront = rangefront/148.

Now I am not sure you really need to convert it in your program. You could just look at the range results and use a calc so you can get a feel for it. your car won't care about the units.

EDIT: heres what keeps haunting me. lets assume most of the time the front is >33.783 inches (5ms pulse divided by 148). that means your interupt will retrigger while in the interupt. Maybe thats ok, as long as you have stack space for all the saves and returns. Also, the reason for changing the servo pulses to interupt drivin from HPWM was to be able to more properly command the servos.

Kenjones1935
- 27th November 2010, 20:37
I have been multiplying by .066 (in my head). Give or take a decimal point. I want to be able to READ the EEPROM and see inches. Not easy?? Is there a PBP routine that does this?

My interrupts are once every 5 millisec. I count 25 of them between each SONAR trigger. They are 125 millisec apart. The servos do work well with properly timed pulses, but they do not seem to react any quicker or with any finer precision. I have no accurate means of measuring this.

Thank you for thinking along with me. My computer experience was all digital data communication. Ultimately I retired from CISCO. I know nothing about real time control systems.

Ken

cncmachineguy
- 27th November 2010, 21:06
I have been multiplying by .066 (in my head). Give or take a decimal point. I want to be able to READ the EEPROM and see inches. Not easy?? Is there a PBP routine that does this?

I think its this easy:


inchesfront = rangefront/148
write SomewhereInEEprom,inchesfront
inchesright = rangeright/148
write SomewhereElseInEEprom,inchesright


To get the result from EEprom:


read SomewhereInEEprom,frontanswer
read SomewhereElseInEEprom,rightanswer



My interrupts are once every 5 millisec. I count 25 of them between each SONAR trigger. They are 125 millisec apart. The servos do work well with properly timed pulses, but they do not seem to react any quicker or with any finer precision. I have no accurate means of measuring this.

Ok, first I have demonstrated my inability to do simple math somewhere in some posts about your sonar timing. But no matter. Heres whats going on right now. you trigger every other sonar 125 mS apart, so if only talking about the right sonar for now, it is triggered every 250 mS, or 4 times per sec. I think that is just too slow!!!. your steering servo can and does react fast enough, but it gets the same signal 12 times before you have a new range to adjust with. So thats 6 missed opportunities to get a better correction.


Thank you for thinking along with me. My computer experience was all digital data communication. Ultimately I retired from CISCO. I know nothing about real time control systems.

Ken

its all fun for me, I am learning PBP far faster this way so its mutually benifical for both. :) And BTW, I switched majors in collage because I didn't want to learn the communication side of electronics. Something about "transform anaylases" just scared me

Kenjones1935
- 28th November 2010, 01:13
I do write SONAR proximity results in EEPROM. I use the WRITE command. It comes out in HEX with reversed words. Here is an example:

Address 00 contains BC
Address 01 contains 02
This reads as BC 02 when looking at the EEPROM readout.

These are HEX and they are reversed. They represent:
$02BC = 256x2 +16x11 + 12 = 512 + 176 + 12 = 700decimal

Take 2/3 of 700 and get about 48 inches. I do that with in my head or with scratch paper.

Your system of dividing 700 by 14.8 gets 47.29 inches. My brain can figure out "two thirds of" easier.

I want addresses 00 and 01 to look like 4729, or preferably rounded down to 0047 or up to 0048. Can PBP do that?

Ken

ScaleRobotics
- 28th November 2010, 12:44
I want addresses 00 and 01 to look like 4729, or preferably rounded down to 0047 or up to 0048.

This will write asci to your eeprom data. Your PicKit2 can be set to read data as asci with the little drop down box. By the way, I hope you are not writing to the eeprom each time a distance is measured, because you will wear your chip out pretty quick that way.



distance var word
inches var byte
distance = 700
distance = distance * 10
distance = distance + 74 'add half of divisor (148) , this is not needed, but will "round up" if you want to be a little more accurate
inches = distance / 148


write 0,61 'For "=" (standard asci character set)
'the + 48 changes it from dec to asci
write 1, inches dig 2 + 48 'will be a "0" if inches = 47
write 2, inches dig 1 + 48 'will be a "4" if inches = 47
write 3, inches dig 0 + 48 'will be a "7" if inches = 47
Then you can view it like this:
4971

Kenjones1935
- 1st December 2010, 00:59
Today I brought both of my PIC controlled cars to the old gym to see how they fared together on the same track. Here's the video. Which do you think was the winner? Remember the TOY car is red. The MODEL car is blue. The TOY cost originally cost $50. The MODEL cost $200. Both have my kit.

http://www.youtube.com/watch?v=7Bw-svW1n3Y

What do you think? Should I show it on Access Television?

Ken

mackrackit
- 1st December 2010, 01:11
They look pretty much equal to me.
What if you took some paste board and made the corners a radius?

Overall they look good!!

Kenjones1935
- 5th December 2010, 01:47
I have a new plan to control the much faster 1/10 scale toy car which is fast, but does not contain proportional controls. The trick is to turn the wheels only for a short period of time (150 msec at the moment) then 'kick' (supplement the springs) them back to neutral.

If the neutral is well calibrated (the 1/10 cars have a knob that centers the wheels) this method makes the car turn with little swerve. I need this while wall following. Otherwise the car crashes into the wall before the code/DPDT relay/steering wheels can react.

I'll make a video if this really works.

Ken

cncmachineguy
- 5th December 2010, 02:19
Great Idea Ken

mackrackit
- 5th December 2010, 03:31
Worked for me :D


Originally Posted by mackrackit :
I just drove home trying to simulate Ken's car. Pulsed the same degrees left or right, more pulses left or right for turns but always the same, say 5 degrees off center, and after each pulse returned to center.

cncmachineguy
- 5th December 2010, 20:04
GEE, I thought no one was listening - LOL

Kenjones1935
- 6th December 2010, 03:27
My toy car has neither toe in nor caster. But it should be able to react. It does not. If you are in a helping mood here is both a (disappointing) video, and a pointer to my code.


http://www.youtube.com/watch?v=ykn8MkGDm28

http://www.employees.org/~kjones/ToyCarKickTurn3.htm

Could the PIC be resetting? Am in a looping loop? The whole thing is only 503 words compiled. My guess is that I am not seeing something that right in front of my eyes...

Ken

mackrackit
- 6th December 2010, 10:43
Wondering if the part in RED is causing the trouble? If it were eliminated and sent to
CheckIfInDanger:
after
keepreversing:
was satisfied???


keepreversing:
WHILE rangefront < stopreversing
' We have not reversed far enough
HIGH stopgo 'go
LOW forrev 'back
GOSUB triggers
WEND

'------------------------------------
'done reversing. Go straight or turn left depending on right
'ping. If > outertrack then out in the middle. If < desiredtrack
'then stuck on wall.
IF rangeright > desiredtrack THEN
'steer left
LOW turnon 'steer
HIGH steerto 'left
steeringstate = 1
HIGH stopgo 'go
HIGH forrev 'forward
PAUSE 500
'hpwm 2,Forward,50 --Already going Forward
ENDIF
GOTO main

Kenjones1935
- 6th December 2010, 16:20
Went to bed last night puzzled.

Checked the car (untouched since disastrous demo yesterday) on the bench. Seemed to react correctly and quickly. The stimuli are my hands moving as quickly as I can make them.

Hmmmm.....

Kenjones1935
- 6th December 2010, 16:37
Could it be that somehow this tight loop eliminates the ability to react to the front SONAR. The video shows the car stuck against the wall in total silence with the front LED constantly on. This WHILE loop could cause that if somehow the two drive motor instructions were being short changed. Maybe I need a PAUSE in here. It would do no harm.


keepreversing:
WHILE rangefront < stopreversing
' We have not reversed far enough
HIGH stopgo 'go
LOW forrev 'back
GOSUB triggers
WEND

Kenjones1935
- 8th December 2010, 00:29
Take a look at:


http://www.youtube.com/watch?v=_4Cm-9W2KNs

Please tell me what you think.:eek:

Ken

cncmachineguy
- 8th December 2010, 01:17
Ken that is just stunning!!!!!

Please share with us the change that made it happen, or was it multiple changes? Looks like now you can tweek the distances to get closer to the wall.

mackrackit
- 8th December 2010, 02:13
COOL!!!!
What did you do??

Kenjones1935
- 8th December 2010, 02:17
The changes were of two types.

1. Instead of "braking" by turning off the DC voltage to the wheels (thereby relying on reverse polarity created by the rolling momentum of the wheels in the DC motor) I now use the DPDT relays to reverse the polarity for a few hundred milliseconds.

2. I put some PAUSE commands in to make sure wheel and steering related commands had time to actually do what I had expected.

Thanks...

Ken

Kenjones1935
- 8th December 2010, 03:56
I put the car up on blocks and found that when going forward it only turned left in my patented incremental way. It also flashed the SONARs at about 1/2 the usual rate.

The Vcc wire for the right side SONAR had become disconnected.

Soooo with the front SONAR working and the right SONAR always saying zero distance to the wall, the car turns left in little bits except when it approaches a wall head on. Then it brakes and swerves left.

That's exactly what my video shows.

Given that information, what if anything should I fix?

Ken

mackrackit
- 8th December 2010, 06:36
Well now you know exactly where the problem is. Connect the side scan and start tweaking that part of the code.

Kenjones1935
- 9th December 2010, 23:17
The issue is controlling the steering. It is bang-bang but I can modify the length of time and the frequency of each 'bang'. The plastic wheels slide easily. This is true of turning as well as forward or reverse drive.

I hope not to introduce an adjustment POT. It appears that the plastic mechanical parts are not consistent. Kicking the steering wheels back from full reach seems not to be symmetric. Hmmmm. :(

Ken

Kenjones1935
- 10th December 2010, 21:46
The car turns left when the right SONAR says it is further away from the wall than "desiredtrack". The car then moves a bit more as it rotates (turning right) its distance to the wall increases as a function of its rotation.

So it decides to keep turning right. Wrong!!

I need to think more about this.

Ken

Kenjones1935
- 11th December 2010, 00:04
I typo'd. The car turns left when the right hand SONAR says it is too close to the wall - ie less than "desiredtrack". It then crosses the imaginary "desiredtrack" line which is parallel to the wall.

Now it starts to turn right - as it should. As the right turn aims the front of the car more at the wall, the right SONAR finds that same wall farther away. It exceeds the "desiredtrack" distance and therefore keeps turning right.

CRASH

ScaleRobotics
- 11th December 2010, 07:45
Now it starts to turn right - as it should. As the right turn aims the front of the car more at the wall, the right SONAR finds that same wall farther away. It exceeds the "desiredtrack" distance and therefore keeps turning right.

CRASH
Sounds like you need to limit your angle as you turn into the wall.

When adjusting right to get to your imaginary line (closer to the wall), if front distance < 3 * side distance, then turn left (until front distance > 3 * side distance). Something like this should help keep from making too big of a right turn, but still get you closer to the wall.

Changing the 3 would change the angle you would allow.

malc-c
- 11th December 2010, 11:10
Take a look at:


http://www.youtube.com/watch?v=_4Cm-9W2KNs

Please tell me what you think.:eek:

Ken

Ken,

Not been following this thread for a while, but simply based on that video my guess is that due to the wheels having limited grip it slides / wheelspins each time the controller nakes an adjustment. If you are able to change the tires for something that grips better you might find it has better control of it's destiny :)

Ioannis
- 11th December 2010, 12:44
Sounds like you need to limit your angle as you turn into the wall.

When adjusting right to get to your imaginary line (closer to the wall), if front distance < 3 * side distance, then turn left (until front distance > 3 * side distance). Something like this should help keep from making too big of a right turn, but still get you closer to the wall.

Changing the 3 would change the angle you would allow.

I am pretty sure this method will lead to oscillations. In fact in the Ken's video this really happens. The car "oscillates" around its desired path.

With simple if-then commands this cannot be compensated. As discussed in previous post, a PID loop control can help.

Ioannis

Kenjones1935
- 12th December 2010, 02:33
it worked better. Now it goes pretty straight but does not turn left hard enough when confronted with a corner. Watching and listening to my video I conclude that at this speed with this little friction the PIC needs more warning (I only gave it 53 inches) to turn sharply left. I'll change that and try again tomorrow. Also this sharp left turn should not be modulated. It should be bang.

It is a bit of a drive to my deserted gym. It has no heat and no electricity. My laptop crashed a few weeks ago. So one fix on my desktop PC, one test.

A question: Do you folks recommend any editor that automates my version control? I would like to start with version 1.0 then activate an editor that automatically adds each of my code changes one batch at a time. If I had that I could recreate any past version.

Presently I am saving the versions identified by their checksum. That is clumsy.

Ken

Kenjones1935
- 12th December 2010, 02:43
I like the sliding robocar. If I want solid control I would go back to the 1/10 scale hobby level car. There are many available rubber compounds for the hobby car wheels. They have caster, toe-in, four wheel drive and weigh four pounds.

Sliding looks like dirt track racing. When I was a kid we had midget car racing with little four cylinder Offenhouser engines on a 1/4 mile dirt oval. I did not do it, but I sure did watch.

Ken

mackrackit
- 12th December 2010, 02:45
Versions..
Might be kind of crude, but I just copy the *.bas file and paste it into the same directory. The the copy has Copy(x) added to the file name. Then the date and time stamp can be referenced.

Kenjones1935
- 12th December 2010, 04:07
How do you keep track of the details of each change? Comments grow and grow and grow...

mackrackit
- 12th December 2010, 04:22
Again kind of crude.
A large comment block at the end of the code. 'Notes
And or a text file. Kind of like a daily log.

I keep current project in DopBox (http://www.dropbox.com/) so I can at least look at the code and take notes in the field on my phone if I do not have a computer with me.

Evernote (http://www.evernote.com/) is pretty good also.

Ioannis
- 12th December 2010, 21:32
Dave,

do you keep the *.bas, *.pbp in the default directory? Does compiler have any problem with the path?

I am considering to keep my files there too.

Ioannis

mackrackit
- 13th December 2010, 00:41
Ioannis,

I let PBP and MPLAB install to their default directories, but my actual code and related project files are kept here.
C:\MAC\My Dropbox\PIC PROGS\"project name here"
Cad/CNC files and such are in a sub directory of the above.

Another benefit from having an off site backup... My CNC machine's PC is also DropBoxed so the machine always has the latest files automatically.

No problems with the path, the path name is still under the length limit this way.

Ioannis
- 13th December 2010, 07:04
OK, Thanks Dave.

Ioannis

Kenjones1935
- 13th December 2010, 23:44
Ladies and gentlemen - I am bamboozled. My 1/10 toy level car seems to be a bit confused also. Garbage in. Garbage out. The old give-no-quarter rule of programming. Is the issue response time? Is the issue inconsistent friction? Is the issue - no it couldn't be - my PBP code? I believe the electronics are consistent and the hookup wires are stable ( I used Silicone household sealant)

In the video I say, "As soon as it starts to turn right, it's in trouble." That now seems not to be the problem. After it successfully negotiates a corner-caused left turn and it is too close to the new wall, it turns left to get out to desiredtrack, but never straightens out.

The code is at: http://www.employees.org/~kjones/ToyCarKickTurn4.htm


http://www.youtube.com/watch?v=7n5_0PlZmzs

Any insight would be greatly appreciated.
Ken

cncmachineguy
- 14th December 2010, 01:01
Its really cool!! It has come a long way, in a very positive way. :)

When its stuck, I see 2 distinct possibilities. the first time when the car was perpendiculer to the wall, my guess was it was too close, therefore the front sensor missed the echo. the second and third times, when it was trying to go forward into the wall, my guess is the angle was just right so as the reflection of the sonar bounced off the wall and kept going forward so the car thought it was all clear ahead.

One time towards the beginning it ran head on into the wall. it went straight back, I am not sure if it bounced or if the car said reverse.

Overall it seems like response time may be the issue. are you able to slow the car when the front is blocked and needs to turn? If so, maybe cut the speed to half when the front is blocked. then on the all clear go back to full ahead. I don't think the car is able to make the turn, check the front, check the side and continue forward.

Kenjones1935
- 14th December 2010, 02:51
I suppose an echo has a significant energy distribution pattern which is a function of the angle on incidence. I do not know the physics but it certainly seems reasonable.

Thank you!

Ken

cncmachineguy
- 14th December 2010, 02:56
I don't know about all that, but if you stand at 1 focal point of a room made in an ellipse shape and wisper, someone standing at the other focal point can hear you clearly. Sonar is just sound, so it stands to reason it has to reflect like a pool ball. :)

mackrackit
- 14th December 2010, 03:01
BATS
Bat navigation....
you are building a bat-car.

Ioannis
- 14th December 2010, 07:21
Friction is sure a problem with your car along with others...

Try to increase the friction with this simple idea.

Cut from a kitchen glove the fingers and place the cut parts on your wheels. I think these will last for a test run, at least.

With the increased friction you will get over the overturning of the car.

Ioannis

Kenjones1935
- 16th December 2010, 03:34
1. I cobbled together the working parts of two DELL 8600 lap tops and created one that works!! I installed the PBP tools and have a strong new battery. I will be able to modify my code in the building - sans electricity and heat - where I test.

2. I found that putting a cardboard right up to the front SONAR makes it behave as if there is nothing within range. Sooo up real close is far away as far as it is concerned.

Kenjones1935
- 17th December 2010, 04:16
Got a new video to show you all. The code is much the same as the last time. I included it below.

The video speaks for itself. Would this be a good context for a public school engineering project? It certainly shows the real world as I know it. The kids could see whether they can make the car go around the room staying outside traffic cones which define the inside of the course.


http://www.youtube.com/watch?v=V2ZjYw9MOz0



'************************************************* ***************
SYMBOL trigright = PORTB.0 ' Define output pin for Trigger pulse
SYMBOL trigfront = PORTB.1 ' Define output pin for Trigger pulse
SYMBOL trigleft = PORTB.3 ' Define output pin for TRigger pulse
SYMBOL echoright = PORTC.6 ' Define input pin for Echo pulse
SYMBOL echofront = PORTC.5 ' Define input pin for Echo pulse
SYMBOL echoleft = PORTC.7 ' Define input pin for Echo pulse
SYMBOL radiotransmitterON = PORTC.4 ' Define input pin for Signal
'inside radio receiver indicatin that the transmitter has
'been turn on. Used to stop the car by turning ON the xmitter.
TRISC = %11110000
DATA $1C,$B5'This version's checksum goes here.
' Speed of sound echo is about 2mS per foot distance.
' define pulsin_max 2800 '28mS SF05 spec says it drops at 30mS.
' don't forget channel 3 every 20mS or 50Hz.
'--------------------

frontdanger CON 180 'about 12 inches. Was 450 about 30 inches
stopreversing CON 390' about 26 inches
frontfree CON 1080 'about 72 inches. Was 800 about 53 inches.
desiredtrack CON 540 'about 36 inches. Now only one line.
'outertrack con 450 'about 30 inches. Was 360 about 24 inches

SYMBOL turnon = PORTC.3 ' the signal that if HIGH makes the car steer straight
SYMBOL steerto = PORTC.2 ' the signal that if on turning is on, then decides
'the direction
SYMBOL stopgo =PORTC.1 ' the signal that if HIGH makes the car go
SYMBOL forrev =PORTC.0 ' the signal that if on and is not on stop makes
'the car reverse

'---------------------------
rangeleft VAR WORD 'experimental timing.
rangeright VAR WORD
rangefront VAR WORD
oldrangeright VAR WORD
oldrangefront VAR WORD
CNTR VAR WORD
CNTR = 0
CNTL VAR WORD
CNTL = 0
steeringstate VAR WORD
steeringstate = 0 ' 0=straight,1=left,2=right,3=skid left,4=rightback,

'--------------
'Looks like I need to kick the steering back into straight.
LOW stopgo 'stop
HIGH turnon
'pause 2000 'Wait so I can put the car down and get out of the way.

main:
GOSUB triggers

CheckIfInDanger:
IF (rangefront < frontdanger) AND (steeringstate <> 3) THEN
HIGH stopgo 'go
LOW forrev 'back
LOW turnon 'steer
LOW steerto 'right
steeringstate = 4
GOTO reverseoutoftrouble
' loop till this is secured
ENDIF

tryleftturn:
IF rangefront < frontfree THEN
'something ahead - turn hard left.
'gosub leftforward
IF (steeringstate <> 3) THEN
HIGH stopgo 'go
LOW forrev 'reverse
LOW turnon 'steer
HIGH steerto 'left
steeringstate = 3 'skid left
PAUSE 150
ENDIF
HIGH steerto 'left
HIGH stopgo 'go
HIGH forrev 'forward
GOTO main 'Loop until secured
ENDIF

goingforward:
keepgoingforward:

IF (rangeright < desiredtrack) THEN
'steer left
CNTL = (CNTL+1)
IF CNTL = 2 THEN
LOW turnon 'steer
HIGH steerto 'left
steeringstate = 1
HIGH stopgo 'go
HIGH forrev 'forward
CNTL = 0
ENDIF
PAUSE 150
ENDIF

IF (rangeright > desiredtrack)THEN
'steer right
CNTR = (CNTR+1)
IF CNTR = 2 THEN
LOW turnon 'steer
LOW steerto 'right
steeringstate = 2
HIGH stopgo 'go
HIGH forrev 'forward
CNTR = 0
ENDIF
PAUSE 150
ENDIF

IF steeringstate = 1 THEN 'left
LOW steerto 'right
PAUSE 100
ENDIF
IF steeringstate = 2 THEN 'right
HIGH steerto 'left
PAUSE 60
ENDIF
HIGH turnon
steeringstate = 0
GOTO main

'-------------------------
reverseoutoftrouble:
' below seems reduncant except for the pause.
LOW turnon 'steer
LOW steerto 'right
steeringstate = 4 'new steeringstate
HIGH stopgo 'go
LOW forrev 'back
PAUSE 200 'added to do some reversing. We have a problem of bumping
'against the wall and not backing up. This pause should fix that.

keepreversing:
WHILE (rangefront < stopreversing) OR ((oldrangefront = rangefront) AND (oldrangeright = rangeright))
' We have not reversed far enough
HIGH stopgo 'go
LOW forrev 'back
PAUSE 250 'maybe this will get car to back off wall
GOSUB triggers
WEND

'------------------------------------
'done reversing. Go straight or turn left depending on right
'ping. If > outertrack then out in the middle. If < desiredtrack
'then stuck on wall. This did not work. See TOY_CAR_KICK_TURN_3.wmv
'Try no IF statement.
'if rangeright > desiredtrack then
'steer left
LOW turnon 'steer
HIGH steerto 'left
steeringstate = 1
HIGH stopgo 'go
HIGH forrev 'forward
PAUSE 250
'hpwm 2,Forward,50 --Already going Forward
'endif
GOTO main
'--------------------------

triggers: ' Check two sonars and xmitter ON signal.
oldrangeright = rangeright
' produce 10uS trigger pulse (must be minimum of 10uS)
LOW trigright
HIGH trigright
HIGH trigright
HIGH trigright
LOW trigright
'zero could be legal below
PULSIN echoright,1,rangeright 'measures the range in 10uS steps
PAUSE 10 'Wait for ringing to stop - read SF05 spec.

'pulsin echoleft,1,rangeleft 'see if this slows the triggers to one
'per second. That it did, but it crashed straight into the wall.

pulsf:
oldrangefront = rangefront
LOW trigfront
HIGH trigfront
HIGH trigfront
HIGH trigfront
LOW trigfront
PULSIN echofront,1,rangefront ' measures the range in 10uS steps
PAUSE 10

radioON:
' make ON = LOW for 1/10 toy car to radiotransmitter
do WHILE radiotransmitterON = 0
LOW stopgo
loop
HIGH stopgo 'get going again
RETURN

END

Ioannis
- 17th December 2010, 12:11
Since you will have a Laptop with you, how about getting telemetry data from your car to analyze them? Like echo, steering acceleration/braking.

Ioannis

Kenjones1935
- 17th December 2010, 18:16
The code is a very simple state machine. I shall post a flow diagram if I can figure out an appropriate CAD tool.

Can (should?) middle school kids be asked to deal with the uncertainties of the real world? I think this TOY level car demonstrates that ambiguity in an appealing and dramatic fashion.

The code consists of a set of hardware related constants which need not be changed.

11 Variable definitions and the following four car behavior constants.

frontdanger - 12 inches
stopreversing - 26 inches
frontfree - 72 inches
desiredtrack - 36 inches

A routine that triggers the SONARS and puts the code in a tight loop when the radio transmitter has been turned on.

Six IF statements. These are each state machines. They evaluate the SENSOR data and tell the wheels what to do. Their labels are:

CheckIfInDanger
TryLeftTurn
TooCloseToWall
TooFarFromWall
ReverseOutOfTrouble
Keepreversing

At one level all the students need to modify are the constants. At another level they can modify these six IF statements. An advanced student could add more states.

Ken

Kenjones1935
- 18th December 2010, 23:40
It's a race. Which car wins? Depends......


http://www.youtube.com/watch?v=YtDu5S1XNh8

Kenjones1935
- 22nd December 2010, 16:36
I suspect a major resistance to getting my robocar into public education is insecurity and uncertainty on the part of the teachers. We are talking about 'how things work' in 2011. My 2004 General Motors automobile contains upwards of 20 PICs. Each tire air valve has a pressure sensor and enough of a computer to maintain a presence on the car's internal wireless network. How did I discover this? I could not make sense of the little tire pressure warning messages on the dash board. A previous owner had rotated the tires. How many public school teachers could explain that in a hands-on way?

Ever tried to explain to a thirteen year old how a microwave oven works?

My robocars are very hands-on and available. All the components are visible including the hook up wire. The little cars react dramatically to programming changes. How do I communicate that to adults schooled in Education, not Engineering or Computer Science.

Ken

rmteo
- 22nd December 2010, 18:28
....Ever tried to explain to a thirteen year old how a microwave oven works?

Ken
How Microwave Cooking Works (http://home.howstuffworks.com/microwave.htm)

mackrackit
- 22nd December 2010, 21:38
Do not under estimate their ability, the kids that is.
One example.
http://www.picbasic.co.uk/forum/showthread.php?t=10200

When YOU take the attitude that something is going to be difficult for someone to learn, then as long as YOU are doing the teaching it will be hard for them to learn.

Children are much easier to teach new concepts to than adults are. Adults "think" they know how things work. Remember the trouble you had with BASIC? That was because your understanding was based on pre-conceived notions from what you learned in the past. Children will not have that problem.

Kenjones1935
- 22nd December 2010, 21:57
However, the only way to reach the students in a public school is through the teachers and the administrators. My question is what is the best way to communicate to them. It is a marketing issue. A teach-the-teacher issue.

Ken

mackrackit
- 23rd December 2010, 08:39
How do I communicate that to adults schooled in Education, not Engineering or Computer Science.
I do not think that should be a problem, many of the users on this forum do not have a formal background in Engineering or Computer Science. I will bet there are plenty of teachers that have RC or some other gadget related hobby. Do they have a "shop" class.

Market to the school district... How many school board members are in local industry? A google search makes me think that Parker has a lot going on in your area, New England Dairy Association, and of course the famous secondary schools in your area should make it easy to convince the schools of the importance.

Kenjones1935
- 24th December 2010, 20:16
I am getting closer. This video shows a 'real' car that can parallel park itself. Using bits from old videos plus some voice over I try to show that making radio control vehicles autonomous is relevant, practical, and fun. I believe there is great potential here for our public schools which are struggling with STEM.


http://www.youtube.com/watch?v=pZCdYcvYgM8

Kenjones1935
- 30th December 2010, 19:31
I've actually made three robots. new

* Reply
* More
o edit
o You can't chill your own stuff :)
o Report Spam

This morning I realized that I have actually made three different robots. Three different RC cars with three different physical charcteristics dictated this.

First I built the 1/10 scale model level car based on an HPI SPRINT. It has detailed miniature suspension and handling features, great speed, and proportional control systems based on pulse width modulation. My PIC kit for this car is simple because the controls are digital signals. All that is needed is the PIC and a DPDT switch. The switch - under PIC control - selects which PWM signals (those from the PIC vs those from the radio receiver) go to the steering and driving electronics. The PIC code is quite simple because of the car's capabilities. At $200 - $300 for the car and my kit this seems too expensive for our public schools.

Second I built a 1/12 scale toy level car. This car has bang bang controls. It requires the PIC, the SONARs and four DPDT relays to steer the DC current into the correct connections. It runs slowly enough for the PIC and the SONARs to keep it within reasonable behavior limits. It can be stopped in mid 'flight' by turning ON the radio transmitter. The price is right for our schools, but I feel the car is not fast enough nor exciting enough. It is also too small to carry my KIT under the car skin.

Third I built the 1/10 scale toy car. This car is much faster than the 1/12 scale toy. It too has no proportional controls. The added electronics kit is the same as the 1/12 car, but the code needed adjusting. ie the 150millisec pulses. I think the $50 car price is within budget. My KIT is complex because of the four relays, but hopefully doable by a dedicated teacher and class. The engineering is interesting because, as one of my videos shows, the behavior is a bit unpredictable. Maybe if I had some local help and a more sophisticated program ------

Ken

Kenjones1935
- 4th January 2011, 22:21
Happy New Year all.....

I have added another video It shows the performance of the 1/10 scale TOY car and two versions of the 1/10 scale MODEL car.

It shows the TOY and a MODEL racing. The lap counter (me) is lacking, but I think the excitement and the attendant appeal to middle school kids is evident.


http://www.youtube.com/watch?v=swYQBZSgtJg

Ken

Magoga
- 6th January 2011, 16:24
Hello friends! Could someone please tell me how to do the PicBasic control two servo motors at the same time, a 100 by sending a pulse and another 50 using PIC16F628A

ScaleRobotics
- 6th January 2011, 16:37
Hello friends! Could someone please tell me how to do the PicBasic control two servo motors at the same time, a 100 by sending a pulse and another 50 using PIC16F628A

How about up to 9 servos? http://www.picbasic.co.uk/forum/content.php?r=270-Driving-up-to-9-servos-with-2-I-O-lines

Kenjones1935
- 15th January 2011, 18:34
Folks, I had an opportunity to show off my robocars on Fitchburg Access Television. I am in the second half of the show. If you like skip the first twenty three minutes twenty seconds.

http://prometheus.fatv.org/media/1273/Inside_Fitchburg_10511/

Kenjones1935
- 20th January 2011, 22:37
Folks,
I have some grande ideas to improve the robotics of my robocars. Trouble is I need what in C are called functions.

Any hope in PICBASIC PRO for my 16F887? You all got any suggestions? My guess is that In order to translate my PICBASIC code to C I will need to learn PIC Assembly so that I can better understand what is really happening.

Has anyone done this? Did he/she create a mid-range PIC set of C libraries?

Ken

rmteo
- 20th January 2011, 23:54
While any C compiler does certainly support functions, there are at least 3 dialects of BASIC for PICs that not only support functions but features such parameter passing, global/local variables, etc. that allow structured programming.

Kenjones1935
- 21st January 2011, 02:37
The code in my little cars is, in fact, very little. It only deals with distance. It does not calculate rates of speed, of approach, of turn. It does not calculate angles. It does no mapping.

Maybe my 16F887 based kit is not up to that task. I am not sure and I do not know how to find out. Maybe I could architect better in C, but it has been literally twenty five years since..... and I used to have a very extensive (corporate supplied) library.

Suggestions?

Ken

rmteo
- 21st January 2011, 03:08
mbed is a tool for Rapid Prototyping with Microcontrollers mBed (http://mbed.org/)

Microcontrollers are getting cheaper, more powerful and more flexible, but there remains a barrier to a host of new applications; someone has to build the first prototype! With mbed, we've focused on getting you there as quickly as possible.

Huge library (check out the Handbook, Cookbook and Code pages), free IDE and C compiler. 100MHz 32-bit MCU, 512kB Flash, 64kB RAM.

Kenjones1935
- 21st January 2011, 17:00
mbed is ARM = RISC. I remember RISC from my days at DEC. For my robocars I chose the Microchip 16F887 because I stumbled upon and bought the PICkit 2 bread board system. Had the PICkit board come with 0.1" centers I would probably stayed with it. Now I use the PIC stand alone and solderless protoboard.

I am afraid to leave Microchip and associated vendors. I bought two UBW32 BITwackers then found that I could not program them with my version of PICKit 2. Also the UBW32 does not come in a 0.1" DIP package. I am also a bit confused where to go for help other than this forum.

Maybe I can stick with PICBASIC PRO if I can teach myself more about doing simple mathematics and array structures for data storage. I surely would like subroutine calls that accept parameters and return values.

Suggestions?

Ken

mackrackit
- 21st January 2011, 17:28
MicroChip also = RISC


I surely would like subroutine calls that accept parameters and return values.

Just write a sub routine that will do what you want and GOSUB. Pretty much the same thing. Yes, the "C" folks will flame this. But it is true.

ScaleRobotics
- 21st January 2011, 17:33
The code in my little cars is, in fact, very little. It only deals with distance. It does not calculate rates of speed, of approach, of turn. It does not calculate angles. It does no mapping.

Maybe my 16F887 based kit is not up to that task. I am not sure and I do not know how to find out. Maybe I could architect better in C, but it has been literally twenty five years since..... and I used to have a very extensive (corporate supplied) library.

Suggestions?

Ken

Hello Ken.

Sure, there are more powerful chips to use. There are also more powerful languages. But, the question is, what are you going to be doing, and do you really need to change chips, and or languages? So far, the use you have made the chip perform, is probably the equivalent of an old man walking with a walker. You have not taxed your current environment whatsoever! Sure, a lot more could be done, but I think, if it was done right, the most required might be an 18F device.

Currently, your PIC18F887 can handle 5 million assembly instructions per second. Your hardware (servo) can handle at maximum, 50 instructions per second (pulse width control at 50 hertz, or 20ms frames). So, with every chance to change your direction, your program can perform 100,000 assembly instructions. A lot of PBP code can fit into 100,000 instructions. That can basically go through every available code location (14k program space) on the chip seven times, during the 20ms it has to make a decision.

Seeing as you are hardly putting a dent in the 14k, shouldn't you at least try to do something more, before saying you don't think the chip can handle it?

Let's take a look at the items you mention:
Speed : This is relatively easy to do and will hardly take any code. Put a sensor on a wheel and away you go!

Approach of turn: You have all the distances measured, why not use them to in your control for turning. Calculate at what point in time will you be x length to the wall, and at this time turn, instead of saying "if my measurement is less than 4 feet, etc etc. Since you are only taking front measurements every 60ms?? or so, you might well be beyond the 4 feet by the time you measure.

Calculate angles: Cool idea. But with what sensors are you going to determine that? And how? PBP has SIN, COS, Hypotenuse and ATAN built in. Sure these are rough calculations, but I don't know that with your current sensors you will need (or be able to use) anything more advanced. Add a magnetometer http://www.sparkfun.com/products/9371 , and perhaps this could get more complex. If it does need to be more precise, there is a PBP compatible CORDIC include file to calculate SIN, COS, ATAN, Hypotenuse. See http://www.picbasic.co.uk/forum/showthread.php?t=10528 . On an 18F, you can do this 9,000 times per second while still using PBP in our program.

As for mapping, with your current set up, I would go out on a limb, and say that is impossible with any language. To map, you need to know where you are. You will need more sensors! A GPS (and a large outdoor "track"), or magnetometer, or light sensors that find at least a reference beacon, or barcode like strips on the floor, just to figure out where it is. Lots of ways to do it, some better than others.

So, from what you have vaguely mentioned, I see no barrier using your current chip, or using PBP. Can you be more specific about what function libraries you are talking about? What ever language you choose, you are going to have to decide how you are going to perform these functions, and what sensors you are going to use to do them.

Kenjones1935
- 21st January 2011, 19:29
I have not been planning on adding sensors. I might change the SONAR for IR. I know nothing about the details.

For speed I was planning on dividing distance traveled by time between measurements. For angles, I agree, the SONAR's have a vague and varying pattern. Hence the 'speed' calculations may be inconsistent.

With the hobby level car I have complete proportional control of both steering and wheel power. If I could get a PWM system that is truly 50htz (my present system is not. It was calibrated by trial and error) then I would have a great deal of flexibility - the better to speed up the car. Then a parameter passing GOSUB would be very convenient.

Ken

ScaleRobotics
- 21st January 2011, 19:57
I have not been planning on adding sensors.

Then it sounds like PBP should be plenty powerful for your application. Only, I don't think you will be able to get into mapping, as there is no reference to where the car currently is. You could count turns, but once you miss or rather add a turn, then you are off. The only angle you could calculate, is the angle between the front location sensed, and the side position sensed in reference to being parallel with the car. You would not know whether this angle is being measured on a corner, or a straight away.

If you want to use accurate servo, you could use some of the code already pointed out to you.

(Ok, this one is kind of new, so no one suggested it yet)
http://www.picbasic.co.uk/forum/content.php?r=270-Driving-up-to-9-servos-with-2-I-O-lines

Back on post #336 of this thread:
http://www.picbasic.co.uk/forum/showthread.php?t=12039&p=91961#post91961

Somewhere way back on this thread:
http://www.picbasic.co.uk/forum/content.php?r=253-2-CH-Hardware-Servo-Driver

And suggested back on post #80 of this thread (though these later examples a lot better)
http://www.picbasic.co.uk/forum/content.php?r=203-PWM-Servo-PWM-encode-decode

Kenjones1935
- 21st January 2011, 21:46
I would like to read a TIMER immediately after sending a trigger pulse to my SONARS. Then immediately reset it for the next cycle. (Which TIMER am I not using with PAUSE or HPWM.) Anybody?

I want to calculate velocity. I plan to subtract two SONAR distance readings and divide by the time elapse between triggers. Units of distance sound travels in a millisecond (13.2 inches) divided by the number of milliseconds. (Could do no translation: Use the distance sound travels in a 4Mhz tick divided by the number of those ticks between SONAR triggers.) Could I explain that to middle school students?

I have not been translating SONAR echo pulses to inches. Instead I learned how to translate inches into SONAR echo times. That is how I set up my distance parameters. At 1100 feet per second that is 13.2 inches per millisecond. (When measuring distance the PIC must divide by two. It is measuring time for an echo response.)

Any simple code snippets you know of?

Ken

Kenjones1935
- 22nd January 2011, 03:01
I would like to use the 4 Meg counter to measure time in seconds and the SONAR responses to measure distance in inches.

I could then set up CONstants that would be recognizable
and measurable by middle school students with a yardstick and a watch with a second hand.

How?

Ken

mackrackit
- 22nd January 2011, 08:57
This displays the sonar distance in inches. Using the "ping" module from Parallex.



' 18F6680
DEFINE OSC 20
@ __CONFIG _CONFIG1H, _OSC_HS_1H
@ __CONFIG _CONFIG2H, _WDT_OFF_2H & _WDTPS_128_2H
@ __CONFIG _CONFIG4L, _LVP_OFF_4L
INCLUDE "modedefs.bas"
DEFINE LCD_DREG PORTG
define LCD_DBIT 0
DEFINE LCD_RSREG PORTE
DEFINE LCD_RSBIT 0
DEFINE LCD_EREG PORTE
DEFINE LCD_EBIT 1
DEFINE LCD_BITS 4
DEFINE LCD_LINES 4
DEFINE LCD_COMMANDUS 3000
DEFINE LCD_DATAUS 150
PAUSE 500
PAUSE 1000

INCONSTANT CON 890
INDISTANCE VAR WORD
TIME VAR WORD

START:
HIGH PORTB.3
PULSOUT PORTB.3,2
PULSIN PORTB.3,1,TIME
INDISTANCE = INCONSTANT ** TIME
LCDOUT $FE,1,DEC3 INDISTANCE," INCHES"
PAUSE 100
GOTO START

Kenjones1935
- 30th January 2011, 02:16
My robocars have no LEDs. They have no debugger and no break points. Using PICkit 2 I can read EEPROM. My code can write in that area using the WRITE command.

When I have my car on blocks connected via the PICkit2 USB cable, I would like to do a READ and see in the EEPROM section some words that the code placed there while it ran represented as decimal numbers.

hex includes the digits 0-9. Is there a library routine or a command to which I can give a WORD containing a positive hexadecimal number (for example the response from a SONAR) and it will return that number in decimal format represented with the digits 0-9 in least significant (as read by PICkit2) to the right?

Ken

ScaleRobotics
- 30th January 2011, 02:33
You mean something like post# 649? http://www.picbasic.co.uk/forum/showthread.php?t=12039&p=96577#post96577

But since you have a Pickit2, it would probably be nice to put your car on a bench, leave your Pickit2 tethered, and use the Uart Tool. You can give all kinds of info from your pic out to your computer screen. You can have it tell you pinged distances for both sensors, etc. It can be a really handy tool for trouble shooting. All you need is some debug statements giving you the right data.

Walter

Kenjones1935
- 30th January 2011, 17:39
At the time of that posting last November I did not understand it. Upon rereading I will try it. Where is the modifier "dig" mentioned and defined? I do not see it. Must be in one of the 'include' files. Yes?

I never figured out how to use the MPLAB debugger. I thought it was only good for simulation running on my PC. I will give it a try.

thanks again...
Ken

ScaleRobotics
- 30th January 2011, 17:56
Hi Ken,

DIG is for digit. Nothing in there needs any include file. Dig is covered in the manual, but you have to look around a little bit for it. DIG returns the value of a decimal digit.

C var byte
D var byte
C=123
D = C DIG 0 ; Makes D = the lowest digit of C (3)

When I mentioned debug, I meant the DEBUG command. It lets you send serial out of any one of your PIC's pins. Then you can use the Uart tool on your Pickit2 to read any value you want. Much simpler than Mplab debugger if you ask me.

5121



http://www.picbasic.co.uk/forum/images/misc/pencil.png

Ioannis
- 30th January 2011, 21:07
Hi Walter.

I saw this picture of Pickit2 with UART connection. Does the PIC connect to Pickit2 as TTL level serial link?

Ioannis

ScaleRobotics
- 30th January 2011, 21:18
Hi Ioannis,

Yes, it takes TTL True, so Ken can do debug something like this for his setup:



DEFINE DEBUG_REG PORTB 'This is set to match the ICSP pins
DEFINE DEBUG_BIT 7 'PIC sends data to the PC on this pin
DEFINE DEBUGIN_BIT 6 'Can be used to receive data from the PC
DEFINE DEBUG_BAUD 38400 'This is the highest baud rate Pickit2 can handle
'It seems to work ok with my 8 mhz stuff and higher
DEFINE DEBUG_MODE 0 'Sets debug to True levels (1 for inverted)

Kenjones1935
- 31st January 2011, 01:23
My PICkit2 communicates with my PIC on its pins 4 and 5 already. Are you saying that after it is downloaded and running, my code can use the same USB wire to talk back to the PC? And I can display what it says using the DEBUG tool.

Ken

ScaleRobotics
- 31st January 2011, 01:34
You got it Ken. Your ICSP pins are RB7 and RB6. I think I have the definitions right for you. So you should be able to get it to talk pretty easy.

Ioannis
- 2nd February 2011, 09:33
As Walter stated, exactly that Ken!

So, this is a great tool. I wonder why Pickit3 does not support this handy idea.... Mysterious way Microchip works...

Ioannis

ScaleRobotics
- 5th February 2011, 18:54
Hello Ken,

Were you able to get your serial link going?

Walter

rtestardi
- 7th February 2011, 04:29
Hi,


However, this one does not come with StickOS installed. But you can use your PicKit2 to install StickOS firmware into it. And, by doing that, you will get the latest 1.80 version. You will need to download a windows driver from this page CPUStick.inf : http://www.cpustick.com/downloads.htm

But with that, and hyper terminal, you can start writing some code. Oh, and you won't get a manual either, so you will have to print one.

Walter

I just stumbled onto this thread...

I'd like to also point out you don't actually need a PicKit2 to program the UBW32, since it comes with the Microchip HID bootloader installed -- you can just download StickOS to the board using the procedure here: http://www.schmalzhaus.com/UBW32/doc/UBW32BootloaderDocumentation.html

Be sure to use the proper version of StickOS for the UBW32: http://www.cpustick.com/downloads/StickOS.UBW32.F512L.v1.80c.elf.hex

I'm definitely game to help folks get this into a classroom setting -- let me know if I can help. (Just drop me an e-mail; unfortunately I'll be out of town for a week starting tomorrow morning.)

One small comment on an earlier post -- if you are using pins rd0-rd4 on the PIC32 and configuring them for PWM/servo mode, then they are controlled in hardware without CPU assistance -- so the BASIC program can do any other things while they are generating pulses, without affecting the pulses.

-- Rich
[email protected]

Kenjones1935
- 15th February 2011, 03:53
For reasons to messy to explain I am trying to get a robocar to run on a blank 32MX460F512L. I was hoping to use Microchip's C compiler pic32-gcc.exe. I am having a very difficult time getting started. Do you know of a beginners example that will take me though step by step?

ScaleRobotics
- 15th February 2011, 19:53
Maybe the folks on the MPLAB C32 Compiler forum can help: http://www.microchip.com/forums/f204.aspx

Kenjones1935
- 27th February 2011, 02:22
I got the PICket 3 to program both my 16F887 and my 32MX460. That's fine, but I am not doing well with C. I have not programmed in C since 1992. In those days I was part of a large corporation that had a support staff.

rich, you mention rd0 - rd4 on the PIC32. I was hoping to see reference of that kind of hardware detail in the PIC32C User's Manual. Nope. No mention of a MACRO either. I have to read the PIC32 Data Sheet? Oh dear.... :o

I am inclined to return to this forum and PICBASIC PRO and 16F887. To work with higher speeds my car needs to know better where it is and what it is doing. It needs some rate of approach calculations and a bit of trigonometry. It needs to increase the number of SONAR triggers per second and their attendant drive wheel and steering adjustments.

I have not pushed the limits of the 16F887. I am not sure how to find them.

Ken

ScaleRobotics
- 27th February 2011, 17:32
rich, you mention rd0 - rd4 on the PIC32. I was hoping to see reference of that kind of hardware detail in the PIC32C User's Manual. Nope. No mention of a MACRO either. I have to read the PIC32 Data Sheet? Oh dear.... :o
Richard is the author of the StickOS operating system. Great to see him here! Yes, RD0 through RD4 are portD.0 through portD.4. They are mentioned in the data sheet, and also labeled (I think) on your board. What macro are you referring to?



I am inclined to return to this forum and PICBASIC PRO and 16F887. To work with higher speeds my car needs to know better where it is and what it is doing. It needs some rate of approach calculations and a bit of trigonometry. It needs to increase the number of SONAR triggers per second and their attendant drive wheel and steering adjustments.

I have not pushed the limits of the 16F887. I am not sure how to find them.
If I remember right, you were caught with a limit of how often you could pulse your sonars. This was made worse by using two of the same type, as you had to wait for the other to be done, as they would get false readings from eachother's echo. I think there was a calculation done way back on this thread about how many feet you would travel at 20mph before you had data back. If I am correct, your limiting factor was your sensors, and not your 5 million or so instructions per second 16F887 chip.

I would agree, I don't think you have pushed the limits of the 16F887. I would go back to the thread about the time your sensors take, and regroup.

Kenjones1935
- 28th February 2011, 02:03
The SONARs respond within a few milliseconds of each trigger. At 1100 feet per second the SONAR hears an echo from a wall five feet away in less than ten msec. There may be problems with the shape of the response pattern and how the ultra sound wave bounces back from a glancing blow. I have no technical means to evaluate that effect.

To figure attack angle I need to have a function that returns the angle given the ratio of the two sides of a triangle, the inverse tangent. I do not see that in PICBASIC PRO. It would be nice in degrees, -90 to 90. With this information I could more intelligently tell the car to turn hard or not-so-hard. It might minimize the weaving down the straightaway.

Calculating velocity would be nice. Without a gauge on the wheels themselves, the only means I know is to divide distance traveled by time. How to get these accurately is iffy in my head.

Gotta do some thinking and experimenting.

Ken

ScaleRobotics
- 28th February 2011, 03:59
Hey Ken, I am often caught taking things too literally, so this may just be another case of that. But from the data sheet (http://www.robot-electronics.co.uk/htm/srf05tech.htm) for the sensor you are using, it says:

The SRF05 can be triggered as fast as every 50mS, or 20 times each second. You should wait 50ms before the next trigger, even if the SRF05 detects a close object and the echo pulse is shorter. This is to ensure the ultrasonic "beep" has faded away and will not cause a false echo on the next ranging.So me taking that literally, since you have two sensors, the best you could get following the data sheet, is every 100 ms. At 20 mph, that's 30 feet per second, or about 3 feet in 100 ms. But maybe 20 mph is a bit fast anyway.

At that rate, you would only be able to steer the servo's every 5 servo pulses, before you got new information from the sensors. But looking on the bright side, you would have time for 500,000 instructions to chew on the data you collected.

Kenjones1935
- 28th February 2011, 18:00
Yes, that is what my SRF05 says too. Presently my code has been pinging at about 5 times per second for each SONAR. I can up that rate.

My thoughts have been that more sophisticated math might give my car better control. I am thinking about mapping - sort of. If the car knows what it is trying to do, where it is relative to the walls and how fast it is going, it may not need so many SONAR pings. I may be just dreaming. I know nothing about classical robot positional and navigational code.

Hmmmmm.... Suggestions anyone? Has the "Robotics for Dummies" paper back been published?

Ken

ScaleRobotics
- 28th February 2011, 18:15
At high speed, I worry that without some sort of reference point, your car will get "lost". If you add a cheap line sensor, you could add something like a 4" black tape reference point to one of the walls or floor beside one of the 4 walls. How accurate are your sonar readings? Can it measure the room from each corner successfully? If not, then you may need to add a cheap wheel sensor to measure distance. Really both of these would be dirt cheap, but yet add a new dimension to your car finding itself, as well as sensing it's speed. (although you could use your sonar to get speed. It would not be accurate as you turn a corner though. It will think you are going backwards as it senses the wall getting further away)


Has the "Robotics for Dummies" paper back been published?I think it's scheduled to be released right after Pic Basic Pro for dummies.:rolleyes:

Kenjones1935
- 28th February 2011, 21:14
The WEB says that a standard hockey rink is 200' by 85' with curved corners on a 10' radius. Here in Fitchburg we have both indoor ice hockey rinks and outdoor street hockey rinks where the players use roller blade skates. The rinks are bounded by an approximately 4' high solid wooden wall.

The advantage here is speed is possible; 25mph +- for electric cars well over that for nitro powered gas engined cars.

I just found a WEB site extolling the 2D IR proximity sensor. Two potential problems - outdoors in bright sunlight and multiple cars. What do you think?:confused:

I did not read the specs for IR sensing. They are talking inches to a few feet. I need at least ten feet, probably more.

http://www.societyofrobots.com/sensors_sharpirrange.shtml

Ken

Kenjones1935
- 28th February 2011, 22:12
I think my little car needs to know where it is relative to the wall it is trying to follow and what maneuver it is presently trying. Right now the code has three states:
1. Trying to go straight along the wall.
2. Trying to turn left sharply because something is in front, but not close enough for state #3.
3. Trying to brake and backup and turn to the left enough so it can return to #1 above.
There is a forth unofficial state in which it is completely lost. It usually gets there from state #2 by turning too successfully. It thinks it is in state #1 but is too far from the wall. If the room is too big it just keeps turning right making a big circle.

It has problems in each case.
In #1 it swerves rather than going straight. If it knew better its rate and angle of approach it could better decide how hard to make its corrective turn.
In #2 if it turns too hard and too successfully it becomes lost. If it does not turn hard enough it finds itself in state #3.
#3 works pretty well except when the front of the car is touching the wall. Something strange sometimes happens then. It just stops. I am not sure why.

My model level car has a POT with which I tell the PIC how fast to go. The top POT position is no where near top speed for this particular model. Associated with each of the seven POT positions are three distances: The ideal distance from the wall. The distance at which the car must enter state #2. The distance at which the car must go to state #3.

I have SONARs, PICBASIC PRO, and 16F887 to work with. Can my cars race inside a hockey rink?

Ken

ScaleRobotics
- 1st March 2011, 15:05
I just found a WEB site extolling the 2D IR proximity sensor. Two potential problems - outdoors in bright sunlight and multiple cars. What do you think?:confused:

I did not read the specs for IR sensing. They are talking inches to a few feet. I need at least ten feet, probably more.

http://www.societyofrobots.com/sensors_sharpirrange.shtml

Ken

Yeah, that was discussed back on post # 617 of this thread. http://www.picbasic.co.uk/forum/showthread.php?t=12039&p=96363#post96363

I thought the object was to be within two feet of the wall, but maybe that changed? I was thinking if you are more than two feet from the wall, turn right. So I am not sure that you really need more than 30 inches of sensing for the side view. Front view, yes, you need more like 15 - 20 feet. Using one sonar and one IR, at least you would be able to take both measurements at the same time, giving you twice the data in the same amount of time.

I would think multiple cars with IR sensors would be a lot happier than multiple cars with sonar. The IR is a spot, where as the sonar is pretty much all over the map with echos etc. As for sunlight, this website (http://www.societyofrobots.com/sensors_sharpirrange.shtml) says "This ranging method is almost immune to interference from ambient light, and offers amazing indifference to the color of the object being detected. In other words, the sensor is capable of detecting a black wall in full sunlight with almost zero noise." But then they go to say "(UPDATE: despite popular belief, it is quite possible for both direct and indirect sunlight to significantly affect results. I learned this the hard way!) " Sounds like some testing is required!
5241

I had another thought about the importance of a wheel speed sensor. If you are measuring vehicle speed with a wheel sensor, you can differentiate the speed that your sonar is picking up to see if the wall is moving toward you at a faster or slower rate than your vehicle is moving. This will tell you if the wall is turning toward you (curved surface), or if you are turning toward a straight wall. This would be helpful for a lot of things. I would say required for better control


I have SONARs, PICBASIC PRO, and 16F887 to work with. Can my cars race inside a hockey rink?As long as they get enough traction, and don't get checked by any of the hockey players.

Kenjones1935
- 2nd March 2011, 02:24
Yes, two feet from the wall is fine when the car is moving at walking speed. At 20mph or more as would be appropriate in a hockey rink I think the car needs more maneuvering room.

The model level cars have rubber tires that can be studded. Since 'indoor' hockey rinks have good enough ventilation to run the Zamboni ice scrapping machine it might be possible to race gas (nitro) driven models in them.

The issue seems to be speed of sensing and accuracy of sensing and using PBP to do the math. I have no idea how to attach a speed measuring device to the wheels of a model car.

Ken

ScaleRobotics
- 2nd March 2011, 04:21
If you used a hall effect sensor like this Melexis 90217 Hall-Effect Sensor:
5245
and put a magnet or two on one of the wheels, then you could use the CCP module with DT_INTS using CCP1_INT to measure the time between pulses. You would measure the circumference of the wheel and do a calculation to get speed. You would do something similar with your front sonar. You would take a reading, and then at a specified time later, take another reading and compare. If you were headed straight for a wall, the distances would be pretty similar, etc, etc.

Here is a hardware example, using hall effect sensor, a lathe, and a basic stamp: http://www.parallax.com/Default.aspx?tabid=420


(http://www.picbasic.co.uk/forum/showthread.php?t=5835)

Kenjones1935
- 5th March 2011, 16:28
Last night I did a successful Compile and Program code for my 16F887 robocar. All looked OKAY. The new code loaded and the car ran. I slept fine.

This morning I added a couple more statements and compiled. Up came four Error[113] comments. So I commented out my changes and recompiled and would you believe Error[113]. The offending symbol is the command "WRITE". I have been WRITE'ng to EEPROM the values of some calculated thresholds for many weeks. This morning, one WRITE and I get the four Error[113\]. They say:
"Error[113] C:\pbp\pbppic14.lib 607: Symbol not previously defined (WRITE)"
each with a different line number.

What the...?

Ken

Kenjones1935
- 5th March 2011, 23:34
When I added the reserved word 'DIG' to each WRITE statement I inadvertently dropped the all important defining word 'WORD'.

What's that about old dogs and new tricks? Seems true after all.

KEn

Kenjones1935
- 11th March 2011, 01:43
It has been a while. Some local 'education' folks have taken an interest in my project. This is good.

Here is a new video. It amply demonstrates what happens when we cross the line from 'code inside a PIC' and the 'real world'. The third segment of the video shows that 'simple' threshold adjustment linear with speed adjustment is not enough. We also have control loop bandwidth issues. Looking closely at the behavior and knowing what I know now I think the intermittent problem was the 7.2 volt battery connection.

Interesting....

http://www.youtube.com/watch?v=eGejd1N_Qcc

thronborg
- 11th March 2011, 16:27
Hello from Newbee!
I searched for Servo Tester and didnt find anything here so here is my problem. I really cant figure out the mathematics for this.
I made a servotester that output a puls from 0.5mS to 2.5mS (Its more than i need)
I have a pot that give an input of 0 to 255.

Q1: How do i get the Pot in one direction 0, to be 0.5mS and in the other direction 255 to be 2.5mS?

Q2: I have a similar problem with the Servo current sensor that give 2.5V at 0mA and 0,25V/mA.

Thanks in advance.

ScaleRobotics
- 11th March 2011, 17:30
I made a servotester that output a puls from 0.5mS to 2.5mS (Its more than i need)
I have a pot that give an input of 0 to 255.

Q1: How do i get the Pot in one direction 0, to be 0.5mS and in the other direction 255 to be 2.5mS?


That depends on your code for the servo tester. You will probably get more response if you either explain what you are doing, or post your code so far.

Kenjones1935
- 11th March 2011, 20:53
thronborg,

You might find the code examples in post #374 helpful. This dates back to August 2010 when I was first incorporating a pot into my system.

Ken

thronborg
- 12th March 2011, 15:32
Hello
Actually i have this code for display the value on a LCD. Now i want the value of 0 to be 1mS puls and 255 to be 2mS puls.

Se attached drawing.


' Name : ServoTester.pbp
' Compiler : PICBASIC PRO Compiler 2.6
' Assembler : PM or MPASM
' Target PIC : PIC16F690 or similar type compatible with LAB-X20 board
' Hardware : LAB-X20 Experimenter Board
' Oscillator : 4MHz external crystal
' Keywords : ADCIN, LCDOUT
' Description : PICBASIC PRO program to read pot and display on LCD.
' FUNKAR ROR EJ

' Define LCD pins
Define LCD_DREG PORTC 'LCD data port
Define LCD_DBIT 0 'LCD data starting bit 0 or 4
Define LCD_RSREG PORTC 'LCD register select port
Define LCD_RSBIT 4 'LCD register select bit
Define LCD_EREG PORTC 'LCD enable port
Define LCD_EBIT 5 'LCD enable bit

' Allocate variables
x Var Byte

ANSEL = %00000100 ' Set PORTA.2 analog, rest digital
ANSELH = %00000000
Pause 100 ' Wait for LCD to start

mainloop:
Adcin 2, x ' Read ADC value on AN2 (PORTA.2)
Lcdout $fe, 1, "Pot1 = ", #x ' Send value to LCD
Pause 50 ' Do it about 10 times a second
Goto mainloop ' Do it forever
End[/I][/I]

Hope this help
Thronborg

5270

rmteo
- 14th March 2011, 14:37
Ken, take a look at this Electronics with Micro-controllers (http://electronics.flosscience.com/)

thronborg
- 15th March 2011, 01:55
Thank's, now i start to understand a little bit more. Its running fine but i got the feeling that i had to much code.

Actually i dont know why i had the ANSEL, ANSELH and ADCON, it seems to work without them. Any ideas?


'************************************************* ***************
'* Name : NimSer.BAS *
'* Date : 3/3/2011 *
'* Notes : Move Servo 1 to 2mS depend on POT value *
'* Show valu in mS on LCD display *
'* For standard servo settings 1-2mS set LOW_servo con 100 *
'* and HIGH_servo CON 200 *
'************************************************* ***************
'Define OSC and ADC
DEFINE OSC 4 ' Set internal Oschillator to 4Mhz
DEFINE ADC_BITS 8 ' Set number of bits in result
DEFINE ADC_CLOCK 2 ' Set clock source (3=rc)
DEFINE ADC_SAMPLEUS 50 ' Set sampling time in uS
' Define LCD pins
Define LCD_DREG PORTC 'LCD data port
Define LCD_DBIT 0 'LCD data starting bit 0 or 4
Define LCD_RSREG PORTC 'LCD register select port
Define LCD_RSBIT 4 'LCD register select bit
Define LCD_EREG PORTC 'LCD enable port
Define LCD_EBIT 5 'LCD enable bit


TRISA = %00001001 ' RA0 = A/D input
ADCON1.7 = 0 ' RA.1 = +Vref, Set PORTA analog and left justify result
PORTb.6 =0 ' Prepare RB0 for high-going pulseout

ANSEL = %00000100 ' Set PORTA.2 analog, rest digital
ANSELH = %00000000

' Variables
outpuls VAR WORD ' Variable for the calculated puls out in mS
POT_POS VAR BYTE ' Pot position CC=0, CCW=255
LOW_servo con 60 ' Min Servo pulse 60= 0.6mS 100=1mS
HIGH_servo CON 200 ' Max Span from LOW_servo to HIGH_servo
' Span 100 gives 100+100 = 200=2mS
Pause 500 ' Wait for LCD to start

MainLoop: ' The Loop start here!
ADCIN 0,POT_POS ' Read A/D channel 0 to variable SVO_POS
outpuls =LOW_servo + (POT_POS *HIGH_servo/255) 'Calculate the outpuls in mS
Lcdout $fe, 1, "POT_POS= ", #POT_POS ' Display POT Valu between 0-255 on line 1
LCDOut $fe,$C0, "Puls= ",DEC (outpuls/100),".", DEC2 outpuls,"mS"' Display pulswith in mS on line 2

PULSOUT portb.6 ,outpuls ' Move servo on pin
PAUSE 20 ' Constant 20mS pulses(low) between outpuls
GOTO MainLoop ' Forever
End


5287

Kenjones1935
- 24th March 2011, 19:44
Hello, I am back with a robocar - PBP question. I wish I had the will power to really study this.

My robocars use HPWM to control the steering and to drive the Electronic Speed Control => DC motor for the wheels. I am trying to calibrate this command given different little cars.

Before the "main:" label I placed some code to make the wheels turn and steer. I discovered that HPWM rides through the PAUSE command sometimes and not other times. It depends on what code precedes the HPWM commands. Immediately below is a case that works. Below that is a case that does not. By not work, I mean the wheels just do not move.The only difference is the presence of the WHILE loop at the beginning.

The WHILE loop at the front checks the power status of the radio transmitter. If channel3 (PORTC.4) is pulsing the radio is receiving a signal from its transmitter. This works. It gives me an opportunity to put the car down on the floor.

What'z up here with HPWM and PAUSE???

-----THIS WORKS: Turn OFF the transmitter and the wheels move---------------

switchtoPIC = 2
WHILE switchtoPIC >= 2
COUNT channel3,65,switchtoPIC
HIGH portc.0
WEND

HPWM 1, Left, 50
HPWM 2, Forward, 50
pause 1000

HPWM 1, HalfLeft, 50
HPWM 2, HalfForward, 50
pause 1000

HPWM 1, Straight, 50
HPWM 2, brake, 50
pause 1000

main:

------THIS DOES NOT WORK. THE WHEELS DO NOT MOVE until main: ----------

HPWM 1, Left, 50
HPWM 2, Forward, 50
pause 1000

HPWM 1, HalfLeft, 50
HPWM 2, HalfForward, 50
pause 1000

HPWM 1, Straight, 50
HPWM 2, brake, 50
pause 1000

main:

Kenjones1935
- 25th March 2011, 02:23
Would it help if I were to show you the assembly language code for the above two compilations?

Ken

Kenjones1935
- 26th March 2011, 15:09
I need help gang. This is definitely a PBP issue. Do you all have any idea where I should start?

Ken

ScaleRobotics
- 26th March 2011, 16:12
Hi Ken,

HPWM is hardware based, so it keeps going while other things happen.

Check out the manual:

It can run continuously in the background
while the program is executing other instructions.

You might try trouble shooting your output signal, to see what is happening.