Showing posts with label RC-Car. Show all posts
Showing posts with label RC-Car. Show all posts

Sunday, 13 September 2020

RC-Car-4-11 PWM car using MQTT

Explaining the title. This is my car number 4, and the 11th version of the software. For what it's worth, I am working on SD card #1  which is 16GB.

2024- August. It wasn't working after I changed the subscriber, so I have rebuilt the card using card 11. 

Installed Raspios Lite 2024-07-04 using the Raspberry Pi Imager on kubuntu and setting a username and password, SSH on, and wifi configuration. 

It booted on Ethernet and I used fing to find the IP address and SSH logged in. 

sudo apt-get install firmware-zd1211.

Sudo apt update

Sudo Apt upgrade

sudo apt install python3-pip


Install ad-hoc networking.

sudo apt-get install dnsmasq hostapd


Plug in Zyxel dongle and reboot. Ifconfig shows current IP's.


sudo nmtui. This works to set both the Ethernet and Wifi IP addresses.


Setting up MQTT

https://pimylifeup.com/raspberry-pi-mosquitto-mqtt-server/

https://bytebeam.io/blog/getting-started-with-mqtt-on-raspberry-pi-using-python/ - Probably better as my Subscriber is written in Python.


sudo apt install mosquitto mosquitto-clients

sudo pip3 install paho-mqtt --break-system-packages was necessary.


So far so good. Get the subscriber stuff into the right place.

Under this new OS, the format is /home/peterm/pi/mqtt...

The old e format didn't have the /peterm/ in it. How do I change the configuration?








                                                              -------------------

Been thinking about a 4 button controller on a Raspberry Pi that I saw, and how I could replace the current system that I have. One post suggested MQTT to talk between Pi's and gave a good reference to it at:

www ref 1

Here is a good explanation:

www ref 2

and look at others of his  to see how to use buttons with a microcontroller. 


www.ref 3

MQTT Client on Android:

www.ref 4

Think about it and try it?

13/9/20 Trying that R-Pi stuff on card#1 

Necessary to install pip:  sudo apt install python3-pip

Note to use pip it is instruction pip3

-------------------

Starting state: Using SD card 1 which previously contained Motion software. 

It is obviously set up with networking for IP ...9 as that works.

Configured for ....8 on bmth-wireless network

Eventually I will need to AP software and firmware for ZD1211 card.

Have added ZD1211 firmware. 

--------------------

Downloaded paho-mqtt as recommended. 

Have copied app.py to file subscriber.py in  /home/mtqq

I need to look at documentation to see how I have to modify this file. 

And also to set up Mosquitto.

www ref 5

You can configure the mosquitto,You will find the mosquitto conf file in etc/mosquitto

-------------------

14/9/20  Some links to setting up Mosquitto

1.www ref 6

2.www ref 7

3. www ref 8

---------------

from the adafruit link [3]:

sudo apt-get install mosquitto mosquitto-clients python-mosquitto

I think that I have done the first two, but not the python one.

Hah- Apt Cannot find python-mosquitto!

After that there are some good examples, but Adafruit bits are needed, so I am going to leave this one aside for now. It shows how to set up security.

---------------

[2] is about setting up a client/Publisher on the R-Pi and I want to set up a subscriber.

---------------

[1] gives a good example of how you can test a setup within a R-Pi.

---------------

16/9/20

According to this, paho-Mqtt is only a python client library, and I still need a broker.www ref 9

Mosquitto is the broker. 

like this for examples using mosquitto:

www ref 10

All examples that I have found for a subscriber call for a 'broker address' and port. 

www ref 11

examples I have found for setting up mosquitto.conf seem too sparse and don't give me what I want. such as Broker name.

I may have been looking at this all wrong and need to treat each function that I want to perform as a seperate client. 

16/9/20 

I have a file called subscriber.py and when I called it by

'python3  subscriber.py' 

it got over the initial lines of code and stopped at 

pi@raspberrypi:~/mqtt $ python3 subscriber.py  
Traceback (most recent call last):
 File "subscriber.py", line 21, in <module>
   import RPi.GPIO as GPIO
ModuleNotFoundError: No module named 'RPi'

Because this is a new build I think that I forgot to add this. 

pip3 install RPi.GPIO

Now no errors displayed. Will look at how to do the loop to action the response to messages. 

17/9/20

Added some lines to try and set up communications

# Create client   --?? Is this the same as User?

client = mqtt.Client(client_id="rc-car-11")

# Connect to broker

client.connect(broker_address,1883,60)

# Subscriber to topic

client.subscribe("rc-car-pwm")

# Run loop

client.loop_forever()


got this response

traceback (most recent call last):
 File "subscriber.py", line 20, in <module>
   client = mqtt.Client(client_id="rc-car-11")
NameError: name 'mqtt' is not defined

changed this line to just mqtt and not mqttClient

import paho.mqtt.client as mqtt

And no errors.

Testing MQTT-Dash  from: www ref 12

set it up with 

192.168.1.8  port 1883

name = rc-car-11

topic = rc-car-pwm

and a button  that gave 'forward' on one press, and 'stop' on the next. 

to see if it was being received by Mosquitto on the Pi I had to add the following:

sudo apt  install mosquitto-clients

and then start this with the command:

mosquitto_sub -h 192.168.1.8 -v -t "rc-car-pwm/#"  

and it showed the messages being received.

Need to look at MQTT-Dash to see if I could set up a number of buttons doing what I wanted each to do. Left/Right will be the difficulty.

Just found www ref 13

Have started to replace flask stuff with While loop. 

Think I need a Def statement as in this

www ref 14

at the beginning of the while loop? 

Looked up Def Keyword. It defines a function see 'Byte of Pi' page 100. 

19/8/20

Used this a lot today to set up subscriber file without While loop. 

4. www ref 15

Now to test. 

Subscriber.py just falls out, no error messages, and no response. 


See the end of this: 

www ref 16

23/9/20 

trying it out, expect errors   - - - yep, debugging. 

Note from the error message question  on a forum that I only need to connect once, not on every loop. I had commented this out.

At the end of the day, added an else command to the on_message function, which called the motorleft LED, and that worked.  So something wrong with the other if and elif commands. 

Took out brackets around 'message ==forward' test.  still didn't work. 

changed  from "forward" to forward to 'forward' . No change, still does not work. 

Added line in on_message routine to print (msg) and this is what I got:

pi@raspberrypi:~/mqtt $ python3 subscriber.py   
<paho.mqtt.client.MQTTMessage object at 0xb6131070>

which is why this routine does not work. 

Added this line to program:

print("Message received-> " + msg.topic + "  " + str(msg.pyload))   # Print  a received message

and this is what I got:

Message received-> rc-car-pwm b'forward'
Message received-> rc-car-pwm b'motorleft'
Message received-> rc-car-pwm b'stop'

change if statement to msg.payload

No, Didn't work. 

-- - - - - - 

Got it working: 

def on_message(client, userdata, message):

  print("Received message '" + str(message.payload) + "' on topic '"   + message.topic + "' with QoS " + str(message.qos))

  if message.payload  == b'forward':

    up_15()

  elif message.payload  ==b'stop':

    on()

  else:

    motorleft()

-- - - - - - - - - - - 


26/10/20  The subscriber program won't start at bootup for some reason. It is in rc.local. 

I am going to try the method 5 mentioned in www ref 18

and call my unit file subscriber.service

Doesn't seem to work and I can't find any error messages. 

pi@raspberrypi:/lib/systemd/system $ sudo service subscriber status
● subscriber.service - My MQTT Subscriber Service
  Loaded: loaded (/lib/systemd/system/subscriber.service; enabled; vendor preset: enabled)
  Active: failed (Result: exit-code) since Mon 2020-10-26 09:35:35 GMT; 29min ago
 Process: 492 ExecStart=/usr/bin/python3 /home/pi/mqtt/subscriber.py (code=exited, status=1/FAILURE)
Main PID: 492 (code=exited, status=1/FAILURE)

Oct 26 09:35:32 raspberrypi systemd[1]: Started My MQTT Subscriber Service.
Oct 26 09:35:35 raspberrypi python3[492]: Traceback (most recent call last):
Oct 26 09:35:35 raspberrypi python3[492]:   File "/home/pi/mqtt/subscriber.py", line 29, in <module>
Oct 26 09:35:35 raspberrypi python3[492]:     import RPi.GPIO as GPIO
Oct 26 09:35:35 raspberrypi python3[492]: ModuleNotFoundError: No module named 'RPi'
Oct 26 09:35:35 raspberrypi systemd[1]: subscriber.service: Main process exited, code=exited, status=1/
Oct 26 09:35:35 raspberrypi systemd[1]: subscriber.service: Failed with result 'exit-code'.

Fixed by uninstalling RPi.GPIO and re-installing using sudo. 
------------------------   ------------------- ------- 
2/11/20 
 Tested today with a 3Com Router as an AP, and it responded much more quickly to commands. 

Now to configure R-Pi as an AP and test.  See previous blog about doing this. 
https://madsmaddad.blogspot.com/2020/02/raspberry-pi-ad-hoc-wireless.html


3/11/20
Have installed Hostapd and dnsmasq. 
It boots to the rc-car wifi. Now I need to find which files I have to change on mosquitto configuration to specify new IP address and also in MQTT-Dash on tablet. 

one is /home/pi/mqtt/subscriber.py   to specify new IP address for subscriber to access Mosquitto.

In MQTT-Dash, just hold down the button for the publisher connection, then select Edit and change the IP address, and it works, Easy-peasy. 

---------------------------------- -------------------
12/11/20
I have discovered how to configure software pwm on pin 12 (Backwards) so that I can move in reverse at less than full speed. A little problem with that at first, but it now works and is hardwired to 30%. 
It didn't like  "  back_pwm.ChangeDutyCycle(30)"
so I took this out of the initialisation and used it: "  back_pwm.start(30)  ". In the past I remember that there was some problem with the ChangeDutyCycle command. 

I did have the program listed above but have taken it out as it has changed quite a bit. If anyone wants it they can ask. 

--------------------------- --------- --------------- 

6/11/20      This should be a seperate Blog post. 

Have discovered this and will convert it to use the Wemos D-1 as the Publisher for a test. 
https://www.instructables.com/The-Universal-MQTT-Remote/

Have ordered 4x20 LCD screen.      had to change program from 16x2
It connects as follows:
gnd
Vcc           Vin. 5v. 
SDA         D2 or GPIO 4
SCL          D1 or GPIO 5


As the program stands it has 4 switches, so I have assigned them as follows:
Forward +15        14, D5 on Wemos, Orange
Stop                      2 , D4 on Wemos, Purple
Reverse                 12, D6 on Wemos, Blue
Left                        13, D7 on Wemos, Grey



14/11/20  connected up with new screen,  fing shows wifi on all devices
arduino IDE serial monitor shows wemos attempting to make mqtt connection multiple times, but of course my R-Pi software does not have the loop to also try that. 
 rebooted pi so see if that worked. 


Arduino Uno compile error:
WARNING: library LiquidCrystal_I2C claims to run on avr architecture(s) and may be incompatible with your current board which runs on esp8266 architecture(s).  This is apparently due to it not specifically specifying esp8166 in the config file.

Because of this I swapped SDA and SCL https://www.instructables.com/Interfacing-LCD-20X4-Display-to-Nodemcu/



Adding Ultrasonic sensor

Sensor has 4 pins

Gnd     Light Blue  to GPIO pin 9 
Echo    green, via 330 Ohm resistor to GPIO Pin 15
Trig      Blue  to GPIO Pin 13
VCC    Grey - to GPIO pin 2
Other resistor to GPIO Pin 25


2021- May 09 
Ben brought me a large RC racing car that he had picked up at the tip. It has a six cell battery, probabbly Nicad by the look of it, Made by Wintonic, a chinese company. It is not on their website which has NiMH and Li-Ion batteries. It has charged. 

The 27MHz chip is a PT 8A978BP and has the same pinouts as other ones that I have had, so will be easy to change for a Raspberry Pi.  I noticed that pin 12 is a Turbo  pin, so might try and make that work, though I don't have a switch to drive it on the controller. 

Got it running and gave up on it as it is so old, pre PWM. 








Sunday, 30 August 2020

State of RC cars August 2020

 Thought that I should get down notes about where I am with these.

Car 1 has disappeared. 

Car 2 has the software to drive a servo for teh steering, and it is using a Raspberry Pi Zero so needs the Wifi dongle.

Car 3 is the basic go/stop software with 200msec  on the steering. It uses the rasberry Pi Zero W.

Car 4 is the one with the big wheels that had a 2.4Ghz receiver that has been replaced by a Raspberry Pi B with Wifi dongle. This now has the software to test PWM for teh drive motor controls. I have this in the folder Robot-7-Flask-PWM. 


I think I'll retire the earlier cars and all new developments will be on car 4. I don't know what they will be. I will have to add reverse  to it though. 


The next thing to do is to put together the videos of all the cars working and post that to Youtube. That might take a while.

9 Sept 2020

Have added reverse to software. I note that in the App.py that forward was pin 12 and backwards pin 16, but to use PWM pin 16 was moved to pin 18.  as the Motor.Forward links were only used  for the reverse, I was able to change the pin assignments of these.  This is obviously the wrong way round for previous cars. 

For the reverse I had to add something to set the PWM to zero, then sleep a short time before doing reverse. A few bugs were ironed out during the process. 


Looking for RC controller stuff for a Raspberry Pi, I came across the following links: 

https://shop.pimoroni.com/products/adafruit-16-channel-pwm-servo-bonnet-for-raspberry-pi?variant=2821150736394&currency=GBP&utm_source=google&utm_medium=cpc&utm_campaign=google+shopping&gclid=Cj0KCQjw-uH6BRDQARIsAI3I-UdoGbdVU0wVKsOCJAsGiiw9ZMeYTE6X-RtvnUTiUlhKIUjIw-PfI7EaAjgJEALw_wcB


https://uk.farnell.com/adafruit/2327/raspberry-pi-pwm-servo-hat-development/dp/2816274?gclid=Cj0KCQjw-uH6BRDQARIsAI3I-UdGdSobItTuJDYXLEFADLZdeedIvkMqmCsglRsPXdGTTD9QidX7MIgaApHNEALw_wcB&gross_price=true&mckv=s_dc|pcrid|459820056211|plid||kword||match||slid||product|2816274|pgrid|104445616701|ptaid|aud-901284956870:pla-304647303753|&CMP=KNC-GUK-SHOPPING-SMEC-Whoops-Newstructure-31Aug2020

https://github.com/bskari/pi-rc#:~:text=pi%2Drc%20is%20a%20program,a%20rather%20powerful%20radio%20transmitter.

-- used a GPIO pin to transmit at 27MHz or 40 MHz? 

-- has a link to a post about how RC works by using a different number of pulses to give the command. 

https://www.instructables.com/id/Raspberry-Pi-RC-Control/


https://www.raspberrypi.org/forums/viewtopic.php?t=157159

- Some guy looking for assistance in doing it.


https://projects.raspberrypi.org/en/projects/remote-control-buggy

Uses Blue-dot program on tablet that uses Bluetooth. Good instructions on how to build a basic 4 button controller.

- - - - 

Been thinking about this 4 button controller on a Raspberry Pi, and how I could replace the current system that I have. One post suggested MQTT to talk between Pi's and gave a good refence to it at:

http://www.steves-internet-guide.com/introduction-to-mqtt-sparkplug-for-iiot/#more-14899

Here is a good explanation:

https://diyi0t.com/microcontroller-to-raspberry-pi-wifi-mqtt-communication/ 

and look at others of his  to see how to use buttons with a microcontroller. 


https://tutorials-raspberrypi.com/raspberry-pi-mqtt-broker-client-wireless-communication/

MQTT Client on Android:

https://play.google.com/store/apps/details?id=net.routix.mqttdash&hl=en_GB  

Think about it and try it?

13/9/20 Trying that R-Pi stuff on card#1 

Necessary to install pip:  sudo apt install python3-pip




Wednesday, 13 May 2020

2020-May- Further experiments with Raspberry PI RC car - Can I make it respond faster

The starting point for this is using the R-Pi as an ad-hoc  connection so that I don't need an access point, as described here:
https://madsmaddad.blogspot.com/2020/02/raspberry-pi-ad-hoc-wireless.html

In a recent issue of Linux Format magazine I found an article about alternate ways of doing all this so I have to try them.

3 things that you can do:
1. Overclock the pi, done with SD card 4 in a R-Pi B and seems to work
2. Modify the amount of RAM that is used, but the Pi-B only has 256 MB so difficult to do and wonder if there is any measurable  advantage.
3. Use different Web interfacing. Article not much use, look further.

As SD disk 7 is the one active in Car3, I'll try overclocking it.
Just set overclocking to 950Mhz (high) from basic 700MHz.

June 8 2020
Just did a search on Speed optimization in Flask. Got some good results

https://stackoverflow.com/questions/39788630/speed-optimisation-in-flask

https://blog.socratic.org/the-one-weird-trick-that-cut-our-flask-page-load-time-by-70-87145335f679

https://damyanon.net/post/flask-series-optimizations/   Don't know how useful this one will be.

https://anthonyblackshaw.me/2018-02-17/speeding-up-url-for-for-flask


I have to think about how I will test these.  One thought is to build a new SD card  for the car 3 and use it as a test bed, or else to use car 2 which I have here and it has the servo steering modification. Thisn one uses SD card 4.  I think car 3 because the reactions will be more obvious.

First step will be to build a new SD card of the software, not forgetting the overclocking modification above.

I have used SD card 10 to duplicate 7. As an aside, I now have a backup of card 7 on my computer.
https://beebom.com/how-clone-raspberry-pi-sd-card-windows-linux-macos/    worked. - No it didn't. the file created was too large to blow onto the repalcement SD card.


I liked this tutorial.
https://towardsdatascience.com/python-webserver-with-flask-and-raspberry-pi-398423cc6f5d

14/6/20 Rebuilding System on another SD card. Connecting from Chrome on PC Via access point wireless, the response is very fast. So perhaps this is where I have to look for speeding up the system. When I have added the AP software to the R-Pi I'll connect the PC to it.

18/6/20 I think that word should be Ethernet, not wireless, But I will build a basic system (No AP)  and try that via Router wireless.

Wireless to Tablet is the slow item, so is it the browser/software in the tablet. How to test that.

20/6/20 The RC-Car on uSD card 4 responds pretty quickly to the tablet.
Must check again card 7 and 10 for response times.

Ethernet to PC - very fast
Ethernet to tablet, nearly as fast  - So that sort of says the Application on the Pi and the Wifi and Browser on the tablet are not holding it back.
Had a thought that it could be the AP software so searched for Hostapd causing slow action, and found hints that I should configure hostapd for wmm=1.

Now to test.
Humph. Wifi AP doesn't work at all. Not on house network or it's own.
from Dmesg:
  18.436844] usb 1-1.2: Direct firmware load for zd1211/zd1211b_ub failed with error -2
[   18.436875] usb 1-1.2: Could not load firmware file zd1211/zd1211b_ub. Error number -2
[   18.436888] zd1211rw 1-1.2:1.0: couldn't load firmware. Error number -2   


Difficult to resolve. Had to remove Hostapd, and update and then Upgrade SD card #7.  One of the things that seems to have happened is that the zd1211 drivers seemed to have disappeared so I had to reload them. That is probably the error above. Have got it working again with external AP, now need to reinstall hostapd and start again. 

                    











Sunday, 26 January 2020

RC Car Steering with PWM and more about Servos

At the end of https://madsmaddad.blogspot.com/2019/07/rc-car-number-3.html I mentioned that I was going to try this. I said that I had binned CAr #2, but it was actually car #1, and #2 was in a box hidden away. This post is about car #2.

After proving that I could use a Raspberry Pi to drive a Servo, I decided to change out the motor drive steering of this car for a servo and adjust the software accordingly to drive it.   The initial video that explained it all was at https://www.youtube.com/watch?v=N5QmZ92uvUo and he explains teh concepts behind PWM control with it. A simpler explanation is at https://www.youtube.com/watch?v=xHDT4CwjUQE

I have got it working but have not yet taken it out on the road because the R-Pi is sitting beside the car like a heart monitor.


Here is the servo in position for steering car I drilled a hole in the steering arm for the servo arm to go through, rather than trying anything fancy like rods as usually seen in RC airplane controls.  The Servo is stuck in place courtesy of my hot glue gun. At the top right of the picture is the original steering motor just pushed out of place. 



Raspberry Pi Model B connected to the Car. All of the pins connected to the second row of the GPIO except for a yellow ground pin.
Pin 2  +5v to Servo Black wire
Pin 6   gnd to Servo Reddish wire
pin 12 to  IC socket pin 11
Pin 16 to IC socket pin 10
Pin 18  PWM to Servo Yellow wire
Pin 9   gnd to IC socket pin 2 (gnd)

See this previous writeup for the IC pinouts on the control board. https://madsmaddad.blogspot.com/2018/03/second-rc-car.html




This shows the IC socket replacing the receiver IC on the driver board. The black connector card connects all the driver outputs to the relevant motor and also brings in the power for the board from the battery pack at the bottom of the picture.

SOFTWARE

This uses  the Flask setup with the Wifi setup as an Access Point so that I can work direct to it from my tablet.

There are three programs required.

Shell script:  Incorporate this in rc.local to make it run at startup,
export FLASK_APP=/home/pi/rc-car/app.py
flask run --host=192.168.1.8

Set IP address to correct address for the Access Point setup.

HTML:

<!DOCTYPE html>

<! developed using https://www.w3schools.com/css/css_grid.asp for the grid 30 Jan2019

<html>
<head>
<title>RC-Car with Flask & PWM steering 20-1-2020</title>
<style>
.grid-container {
  display: grid;
  grid-template-columns: auto auto auto auto;
  background-color: #ffffff;
  padding: 10px;
  grid-column-gap: 20px;
  grid-row-gap: 50px;
}
.grid-item {
  background-color: rgba(255, 255, 255, 0.8);
  border: 3px solid rgba(0, 0, 0, 0.8);
  padding: 20px;
  font-size: 50px;
  text-align: center;
}
</style>
</head>
<body>

<h1 align="center">RC-Car with Flask & PWM 20-1-2020</h1>


<div class="grid-container">
  <div class="grid-item"></div>
  <div class="grid-item"></div>
  <div class="grid-item">
    <a href="/motor-forwards/" data-toggle="tooltip" title="Forward" class="btn btn-success">Forward</a>
    </div>
   <div class="grid-item"></div>

  <div class="grid-item">
    <a href="/motor-left/" data-toggle="tooltip" title="Left-Left-Left!" class="btn btn-success">Turn Left</a>
    </div>
    <div class="grid-item">
    <a href="/turn-center/" data-toggle="tooltip" title="Left-Left-Left!" class="btn btn-success">Center</a>
    </div>
  <div class="grid-item">
    <a href="/motor-stop/" data-toggle="tooltip" title="Stop Motors"  class="btn btn-danger">STOP</a>
    </div>
  <div class="grid-item">
     <a href="/motor-right/" data-toggle="tooltip" title="Turn right!" class="btn btn-success">Turn Right</a>
    </div>
  <div class="grid-item"></div>
  <div class="grid-item"></div>
  <div class="grid-item">
    <a href="/motor-backwards/" data-toggle="tooltip" title="Reverse!"  class="btn btn-warning">Backward</a>
    </div>
  <div class="grid-item"></div>
</div>

</body>
</html>


Note that I have used W3Schools for a lot of help in getting my HTML correct. Some of the bits in each line referencing the contents of a box are possibly redundant. They were there in the code where I pinched the stuff.  [ see below for simplified stuff].

PYTHON:

# 2020-1-20 Modifications to drive steering using a servo and PWM.  Because I
# don't know if gpiozero and RPi.GPIO can work together I'll remove the GPIOzero and motor
# command.  motor = Motor(forward=12, backward=16)
# look at ancient code for motor handling.
#  2018-04-05 Modified from Les Pounder program to handle two motors
# one for steering and one for motion
# steering is Left = 10, right = 11
# changing it trying to add Turn for motor control
# 2018-10-31 changing toggle LED to stop motors

from flask import Flask, render_template
from time import sleep
import RPi.GPIO as GPIO

#Set GPIO Numbering mode

GPIO.setmode(GPIO.BOARD)

# set pins for motor control

GPIO.setup(12,GPIO.OUT)
GPIO.setup(16,GPIO.OUT)

# set pin 18 as Output for Servo Steering
GPIO.setup(18,GPIO.OUT)
servo_st = GPIO.PWM(18,50)

#start PWM running on servo, init value 0 (pulse off)
servo_st.start(0)
# servo runs from duty cycle 2 to duty cycle 12, 7 being central position  for servo used in youtube demo.
# define variable duty
duty = 2

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/motor-stop/')
def on():
    GPIO.output(12,False)
    GPIO.output(16,False)
    return render_template('index.html')

@app.route('/motor-forwards/')
def motorforwards():
    GPIO.output(12,True)
    GPIO.output(16,False)
    return render_template('index.html')

@app.route('/motor-backwards/')
def motorbackwards():
    GPIO.output(12,False)
    GPIO.output(16,True)
    return render_template('index.html')

@app.route('/motor-left/')
def motorleft():
    duty = 2
    servo_st.start(duty)
    sleep(1.3)
    servo_st.ChangeDutyCycle(0)
    return render_template('index.html')

@app.route('/turn-center/')
def centersteering():
    duty = 7
    servo_st.start(duty)
    sleep(0.3)
    servo_st.ChangeDutyCycle(0)
    return render_template('index.html')

@app.route('/motor-right/')
def motorright():
    duty = 15
    servo_st.start(duty)
    sleep(0.3)
    servo_st.ChangeDutyCycle(0)
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')


The major changes in this, other than PWM operation, is the change to GPIO Board numbering rather than GPIO Name numbering.  Also I stopped using GPIOzero, so have reverted to direct control of pins in the software. I like this better. Comments can be used to explain functions that are not clear.


Questions: I am happy to answer them, but they may be already answered in previous posts.

27/1/2020  corrections and simplifications
The  line
 <a href="/motor-forwards/" data-toggle="tooltip" title="Forward" class="btn btn-success">Forward</a>

can be simplified by removing things that don't serve any purpose in this case. It becomes:
 <a href="/motor-forwards/" >Forward</a>


SERVOS

I was given a box of Servos and after having problems with the one that I had put in the car, I went through them plugging them into the Raspberry Pi.

Four of them totally didn't work and caused the R-Pi to shut down.  These were all small ones without labels.

Some of them partially worked.

Here is a breakdown of what happened. The software is set to duty cycle 2 for a Left turn, 7 for a centre position, and 15 for a right turn. I noticed that in some cases the servo shaft turned CCW when I expected CW, and am now confused as to which is left and right.

Device                                               Left               Centre           Right
small unit with black arm.                   x                     ?                    ?

Small unit with white arm                  -90                    0                 +90 (CW)

Digifleet FPS-20                                 -60                    0                 +60

Digifleet FPS-30   dead kills Pi.

Aristocraft HS-100                            -90                increments              increments
'increments' possibly means that I have to extend the range. needs testing

GWS Mini STD                                +90                    0                  -90

Tower Pro Airplane 99                            iffy, slow to respond

Small Black with arm                       +110             no response         -100

Black, short wires                            +110                                          -90

Digifleet FPS33 (2)       dead

Black with black arm.           dead

Powermax Skyranger 5 white-X arm      +75                steps                           -70

Steps/increments probably means that I have to expand the range from 2-7-15.

Another bothersome feature of these servos is that the arms, or whatever the proper term for them is, are different sizes and shapes so are not transferrable from one unit to another. Most are splined, but some are square.

2020-02-08  See https://en.wikipedia.org/wiki/Servo_control

It is not duty cycle that is important, it is pulse width, generally between 1msec to 2 msec wide.
Now I am using a value of duty 2-7-12  with a pulse rate of 50 Hertz.


Also:
https://learn.adafruit.com/adafruit-raspberry-pi-lesson-9-controlling-a-dc-motor/software

and

https://github.com/sarfata/pi-blaster








Thursday, 11 July 2019

RC Car Number 3

This car has thrown a curve ball. The Receiver IC is a SM6135W and it has the same pinouts as the IC in Car 2, so I would expect the car to behave the same. But it doesn't. This is using the Flask software with the Raspberry Pi 3W configured as an Access Point.
In Car 3  Forward makes the wheels turn Left, and Backwards turns Right, And the Left/Right buttons make the car go backwards or forward for a very short time.

But the IC has the same pinouts as shown here:

Here is a picture of the driver board, with the receiver IC replaced by an IC socket



The Blue and White wires drive the steering motor, and the Yellow and Grey wires drive the main motor.  The Red and Black wires are the power. On the second picture, above the grey wire is a block of 6 pinouts that the blue wire connects to and a sort of Z shaped set of pinouts where the white wire connects.


I am going to replace it with a HW-95 driver board to see if it works properly.



This has a +5 connection and a +12 connection. I don't know which to use yet. 


A comprehensive video is here: 
and another


If I can get it working basically, I might then try to use PWM to drive the motors.

2019-07-13 I have it working, but of course it is efectively an eviscerated car with the L298 motor controller driven by the Raspberry Pi. The car batteries 6x 1.5 AA cells are connected to the +5v input on the controller and the car crawls very slowly and doesn't have enough power to back up the very smallest of slopes (Driveway).

At least crawling this slowly it doesn't get away from me. Another 'feature' is that the steering wheels do not have an automatic return to zero as car #2 did. 

I'll move these batteries to the +12 terminal and see if it makes a difference. RESULT: It makes a terrific  difference. The car runs like it should. The next problem is what to do after it has run into something and ceases to respond. The first time this happened the power cord had pulled out of the R-Pi. I don't know what happened the next time. 

2019-07-28 Here is the proof: https://www.youtube.com/watch?v=jsj-cnHkr_k&t=9s

Next is to replace the original card, but swap the steering and motive motor wires. I have a record of where they were connected on the board. 


2020-01-14 New thoughts. 
I have just watched a video about driving multiple Servos from a Raspberry Pi:  https://www.youtube.com/watch?v=xHDT4CwjUQE
and then one about autonomous vehicles - farming implements, so it caused me to look at Autonomous vehicles driven using a Raspberry Pi so I found this: 

This one uses a Servo Shield(Hat). My thoughts turned to controlling the steering using a Servo. I wish that I had not dumped Car #2 as I could have used that. It's steering was never any good. 

Watch this space?

2020-06-08 
Been a while. 

It should be noted that this is using uSD card #7. 

I have put the original driver board back in, and created brackets to hold the R-Pi ZeroW in place. It runs well, but is slow to respond. In the field with grass tufts it didn't seem to have power to get over them.  Maybe I need to get an adjustable ramp and see how steep it can go?  One thought here is that the outputs of the GPIO are  +3 volts approx where the original receiver chip was a +9 volt system. If I had a buffer to give a greater output voltage to the driver board would it have more power, or just go faster.  This is not an easy thing to implement.  Documentation is confusing but suggests that IC is +5v and output is 3v, so is OK. 

I discovered that the steering return to home mechanism was gone, so I created one with a paper clip and it seems to work. However the steering software only turns it for one second. I am going to increase this to two seconds. 

Going up the road it is sensitive to camber and doesn't react well to being asked to steer up the camber. 

The steering has now been changed to two seconds and then it has a stop command so the steering returns to zero position. Maybe I should adjust the software to have a center steering button and no time set?











Sunday, 26 May 2019

RC car improvements up to June 2019 - and a future possibility?

Car number 2 works with the software on SD card #3, but the problem is that it takes off too fast and needs a lot more room than I have to fully test it. It also doesn't respond very quickly to the tablet.

I'll give it a go with SD card #7, which has the AP built in and see if that is any better.

- 2019-06-13 Car number 2 with R-Pi3W and Card#7 out on the road, it works aside from the fact that left and right are wrong way around, just not very fast to respond. Is it worth doing a video showing it?
- How can I improve response times?


----------------------------

Because of the things that I have found out about pwm for driving the RC airplane servo's I might try and make the forward/back work using pwm with every press of the 'forward' button adding 5% to the pwm pulsewidth.

At the moment struggling to get basic pwm operation working in the program instead of go/stop.

---------------------------
9/9/2019
I did get this working.  One of the things about PWM is that driving Remote Control Servos
uses PWM of about 1.5% to 2.5% ( these are just approx figures from my mind, check elsewhere for actual limits) To drive the car motors I noticed that it didn't do anything at 5% PWM, so I made it increase in steps of 15% and this worked fine. Another challenge was getting the feedback to display in the HTML the figure of the PWM value.

Here is the python code for the car: [some comments removed]

from flask import Flask, render_template

# This gives us control of the Raspberry Pi's pins.
import RPi.GPIO as GPIO
import time

# Tell it which pin number we'll  be using to refer to the GPIO pins.
# We will use the physical pin ordering. Set initial state of pins
GPIO.setmode(GPIO.BOARD)

MotorFwd = 12
MotorBack = 16
MotorLeft = 19
MotorRight = 23
GPIO.setup(MotorFwd, GPIO.OUT)
GPIO.setup(MotorBack, GPIO.OUT)
GPIO.setup(MotorLeft, GPIO.OUT)
GPIO.setup(MotorRight, GPIO.OUT)

# PWM pin
u_d_pin_no = 18
GPIO.setup(u_d_pin_no, GPIO.OUT)


frequency_hertz = 50
pwm = GPIO.PWM(u_d_pin_no, frequency_hertz)

PWM_Stop = 0
PWM_value = 0
PWM_increment = 3
# becomes 15 after calculations

# total number of milliseconds in a a cycle.  Given this, we will then
# know both how long we want to pulse in this cycle and how long tghe
# cycle itself is.  That is all we need to calculate a duty cycle as
# a percentage.
ms_per_cycle = 1000 / frequency_hertz

# now lets get into Flask

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/motor-stop/')
def on():
    # motor.stop()
    PWM_value = 0
    duty_cycle_percentage = PWM_value
#    print("Duty Cycle[S]: " + str(duty_cycle_percentage))
    pwm.start(duty_cycle_percentage)
    return render_template('index.html')


@app.route('/up_15/')
def up_15():
    global PWM_value
    PWM_value = PWM_value + PWM_increment
    duty_cycle_percentage = PWM_value * 100 / ms_per_cycle
#    print("Duty Cycle[F]: " + str(duty_cycle_percentage))
    pwm.start(duty_cycle_percentage)
#    time.sleep(.5)
#    pwm.ChangeDutyCycle(0)
    return render_template('index.html', PWM_PC = duty_cycle_percentage)

@app.route('/down_15/')
def down_15():
    global PWM_value
    if (PWM_value > 0) :
        PWM_value = PWM_value - PWM_increment
        duty_cycle_percentage = PWM_value * 100 / ms_per_cycle
#        print("Duty Cycle[F]: " + str(duty_cycle_percentage))
        pwm.start(duty_cycle_percentage)
#        time.sleep(.5)
#        pwm.ChangeDutyCycle(0)
#    endif
    return render_template('index.html')

@app.route('/motor-left/')
def motorleft():
    GPIO.output(MotorLeft,GPIO.HIGH)
    GPIO.output(MotorRight, GPIO.LOW)
    time.sleep(1)
    GPIO.output(MotorLeft, GPIO.LOW)
    return render_template('index.html')

@app.route('/motor-right/')
def motorright():
    GPIO.output(MotorLeft, GPIO.LOW)
    GPIO.output(MotorRight, GPIO.HIGH)
    time.sleep(1)
    GPIO.output(MotorRight, GPIO.LOW)
    return render_template('index.html')


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')
# We have shut all our stuff down but we should do a complete
# close on all GPIO stuff.  There's only one copy of real hardware.
# We need to be polite and put it back the way we found it.
    pwm.stop()
    GPIO.cleanup()

--------------------------

Having done all this I decided to do an R/C boat as it would combine the motor drive and the servo drive. I have given up on this idea because 1] I don't have a boat  2] the little motor that I was going to use didn't work with PWM and 3] I don't have a propellor.


Friday, 17 May 2019

Four(!) RC cars now

May-2019
I seem to have been collecting cars to experiment on. This is what I have now.

Car #1  The one in the video, It was using a program called WebIOpi that became obsolete after an update to Raspbian. Also the original driver board broke after it was touched wrongly and has now been replaced by a Deek-Robot board. It still works.


and the deek-robot driver board. 
I only paid about a pound for this, but it works fine. 

Car # 2
This has taken a bit of work to get going because I have been trying to make a harness that can be moved between cars. What drove this is that Cars 1,2 &3 all have a 16 pin dual in-line receiver chip on them that have the same pinouts for forward and back, left and right.  On car 2 I replaced the IC with a DIL socket. The software that this is using is built on Flask from an article in Linux Format. 





Car #3 I have not touched this one yet, but as can be seen, it has the 16 pin DIL chip there for when I do get around to it.


This one was a 40MHz radio. It's the one that gave me the idea to make a common interface connection from the Raspberry Pi. 

Car #4 This one has a 16 pin IC surface mount and a bit smaller, but I'll bet that the pinouts are the same.  I'll have to modify the connections from my 16 pin DIL Header to connect to it. This one says it is 2.4GHz and it is a Maisto brand. Because of my history with Wifi with Telxon and the university, I wanted to try and drive it directly but a previous blog describes why this idea was a non-starter. 



That's it to date. Next step is to post a video of car #2 in operation.

25 June 2019:

In Car 2 the IC that has been replaced by a socket so that the harness from the R-Pi can plug straight in  has the following pinouts. This enabled me to build the harness. Note that the poor creation of this jpg has the 'right' label too high and it should be on pin 6.


Now the pinouts for the IC from Car 3 are as follows:

Which is the same.  For anybody who wants to check this, car 3 is a 40MHz unit using SM6135W IC and car 2 was a 27MHz and I'll have to look back in these blogs to find the IC part number.

The reason for belabouring this point is that with the R-Pi3w and the software in card #7, car 2 behaves well, but car 3 is all topsy turvy in that the L/R buttons make it go Forward/Backward, and the F/B buttons turn the car.  I don't understand it.




Thursday, 25 April 2019

2.4GHz RC cars and WiFi, A history and Investigation

This all came about because of my little hobby of reworking RC cars to be controlled by Raspberry Pi computers.

An early aside: In my last iteration I discovered that not all Wifi dongles are capable of being configured as Wifi Access points.   Here is how to discover that:
  https://wiki.archlinux.org/index.php/software_access_point

OK, I recently picked up a car that is labelled 2.4GHz and I wanted to know if I could connect to it with my Android tablet as I do with my other experiments. Neither Fing or Wifi analyzer programs would 'see'  the car. I begasn to wonder if perhaps it was using a different  2.4GHz physical layer, not DSSS (Direct Sequence) as I was used to in the old days of Telxon. The manufacturers of these cars do not give out any information about it, I can't even find a configuration manual.

This got me wondering what the current way of using wifi is, so I found this: https://en.wikipedia.org/wiki/IEEE_802.11
It does not mention in detail where these variations are used.

I started looking at the history of Wifi to see if there was anything there and found that the recorded history does not fit with my memories. https://en.wikipedia.org/wiki/Symbol_Technologies is  the view from a Symbol  Technologies viewpoint and this leaves out such a lot: http://www.fundinguniverse.com/company-histories/telxon-corporation-history/

Telxon acquired Telesystems Corporation. Their first offering was in the 900MHz band, but they soon moved up to the 2.4GHz band, though the radio was quite large to fit into the form factor of a Telxon PTC. I think this radio was called the 022 version.  They wanted a smaller radio and soon there was the 025 radio which was about 1.5 inches square and fit very nicely into a Telxon PTC.
What isn't mentioned is that Telxon sold the wireless division now called Aironet, to Cisco. This is mentioned here: https://en.wikipedia.org/wiki/Aironet_Wireless_Communications

Things have moved on since the great DSSS/FHSS fights with Symbol and now it seems that the common mode is OFDM   Orthogonal Frequency Division Multiplexing.

My investigation found this site that discusses the fact that different manufacturers use different forms of Wireless, some DSSS and some FHSS and some mixed, and that they are not compatible with each other, so the receiver must match the transmitter.
http://rcmodelreviews.com/spreadspectrum01.shtml  You need to get to page 5 at least.

Enough.




Monday, 30 April 2018

RC-Car using Flask

WebIOPi is dead. It doesn't work with the latest raspbian.

[2018-10-15]
I have been trying other IOT programs without success.
In Linux Format October 2017 LXF229 there was an article about using Flask with an example.
sudo apt-get install python3-flask.
mkdir rc-far
cd rc-car
mkdir templates
save app.py in the rc-car directory
save index.html in the templates directory

[Need to install filezilla and transfer files to the Pi. Need to debug.] - leave for now. Copied and pasted contents of files using nano.

to test: browse from another device to 192.168.1.8:5000

[2018-10-16] created script with two lines as below and it worked.
Problems. Cannot stop forward/backward.
2. formatting of HTML.

[2020-8-26] Latest version of Raspian -Buster does not contain gpiozero

sudo apt install python3-gpiozero  needs to be done.


[2018-4-30]
It didn't work because the author Les Pounder forgot to add one or two steps. He was very quick to reply to me and we got it sorted.  The lines that I needed were:
export FLASK_APP=/home/pi/rc-car/app.py
flask run –host=192.168.1.8

I have now put these into a shell script file that I run to start things happening.

My file structure is
/home/pi/rc-car/template/jquery

It made use of GpioZero libraries that are different to those I was using before.  The main problem was that his example only seemed to use one motor, and I have two motors.  I did get it working to drive the main wheels.

A search found an example using flask that did have two motors, but this is one on each wheel, whereas my configuration is one to drive forwards and backwards, and one to turn the front wheels.
This is from a github example by Kevin Olson https://github.com/olsonk/web-robot
I put this on the Pi and it failed. I have sorted out one of the problems. In the app.py program the debugging print statements are in the wrong format. They have now changed to a function call and need the parameters in ().  Sorted, But it still fails.
I have found an email for kevin Olson and asked him. We shall see.
The Html file calls a javascript that is in a certain place. I don't have it. I tried to download  jquery and apt-get said I had the latest version.  I have now found a version on-line at https://code.jquery.com/jquery-3.3.1.js
 and created a folder 'jquery' and put this file in there, edited the html, and am ready to test.

Aside: For what it's worth, I have replaced the motor drivers by the Deek-Robot  board using the L293D chip. http://www.deek-robot.com/productshow.asp?id=17&small=4



I had changed the text in the index .html file from {{ Title}} to {{ RC-6 Olson model }} . It didn't like that. I think Title within {{...}} is passed over from the app.py?

Also it failed because it didn't like the file name index.html. I changed it to main.html and it worked. The browser sees it. Unfortunately the LEDs do not work. I always have this problem with identifying them, and I wonder if GPioZero Libraries use different numbering than I am used to.

Tomorrow?
2018-05-02 Not touched code. I bolted the Raspberry Pi zero down to the car chassis. It required making two flanges from an old plastic box and drilling the holes in it to attach it via the Meccano bolts and some very fine bolts that I found in my junk box. The RC car was a Meccano toy originally. I also cut down a piece of dowel to act as a mast for the Wireless dongle as the R-Pi zero has a 4 inch converter cable from micro-USB to USB.

GPIO Pins                   Wire Colour             Deek-Robot
6                                    Black                         GND
12                                  Orange                       In1
16                                  green                          In2
17                                  Red                            In4
21                                  Yellow                       In3

This seems to work all backwards using the WebIOPi program Left = right, FWD = Backwd.



2018-05-08
Catching up. I got it working  using Les Pounders programs. New problem is that forward backward only stay on for a short period.  I got rid of the Internet stuff by using the jscript stuff that i installed following the Olson instructions.

Here are the motor controls.   the sleep lines are commented out.
led = LED(25)
motor = Motor(forward=18, backward=23)
turn  = Motor(forward=10, backward=11) 


In LP's stuff the html is tidier, but doesn't put nice boxes. This is all in one line across the page with wrapping.

   Click on the buttons to trigger the action
                                                               

   

                                                                                       
    Motor Forward    
    Toggle LED       
    Motor Backward
    Motor Left   
    Motor Right
   


Here is the Olson code: 

                                  
               

               


                       
                       
               

               


                       
               

                


which does have separate lines for the Left/right 'buttons' 

Need to think about how I do it for the first one. 
Note. This writeup doesn't show the code, it shows the result. How do I fix that? 

--> No. LP stuff does have boxes, Forward/LED/Backward on the first line, and Left/right on the next line. It does use an external bit of code.  Problem is, I can only turn off forward by pressing Backward. LED Toggle works, and because I have forward/backward selected, I can't do Left/Right. 
Hmm.

2019-04-26

Update, I now have another car, labelled '2' It has the Raspberry Pi with SD card #3 in it which is the Flask code, but still requires an access point. Card #4 and #7 have the access point in the R-Pi so are not tethered to an Access point.

Anyway, yesterday I tried this car and noticed the ground wire between the R-Pi and the driver board started smoking and melting. Today it doesn't work, now that the wire has been rerouted. The batteries are good on both parts.  The R-Pi has been tested on my test rig and is OK.  The main difference since I 'built' this car some months ago are that the the wires now go from the R-Pi to the board through two 16 pin Dil Headers, one with the wires soldered into it and one on the board where the IC was.

OK, I tested without the driver board powered and just cheking the outputs of the R-Pi on to the board, and they were all coming out as -4.56V. Whoo!. What I discovered is that the ground wire to teh R-Pi was on pin4 (+5V), not pin 6 as it should be.  Fired it all up again and it sort of works, except everything is backwards. Forward on the web page makes it go backward, and Left turns Right!. Easy to fix.

Lets make the following changes:
GPIO pin 12 = brown  --> Red
GPIO pin 16 = red   -->Brown

GPIO Pin 23 = White --> Black
GPIO Pin 19 = Black --> White

One pin on the IC on the driver board does not make a connection so needs resoldering.