Wednesday 23 December 2020

Realtek Dongle on Raspberry Pi

I bought one hoping that it would be a drop-in job to replace my Zyxel big dongle, but it isn't.

Dmesg shows  the dongle:

   5.343207] usb 1-1.2: New USB device found, idVendor=0bda, idProduct=f179, bcdDevice= 0.00
[    5.358273] usb 1-1.2: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[    5.369210] usb 1-1.2: Product: 802.11n
[    5.376550] usb 1-1.2: Manufacturer: Realtek
[    5.384275] usb 1-1.2: SerialNumber: 00E0222F6C96

But that's as far as it goes.

lsusb gives:

pi@raspberrypi:~ $ lsusb
Bus 001 Device 004: ID 0bda:f179 Realtek Semiconductor Corp. 

lsmod shows some wifi stuff, but nothing definitive.

and iwconfig:

pi@raspberrypi:~ $ iwconfig
eth0      no wireless extensions.

lo        no wireless extensions.

A search shows that I have to build the driver:

https://www.raspberrypi.org/forums/viewtopic.php?f=28&t=62371

I was hoping that I wouldn't have to do this, though the author indicates that he has made it as easy as possible. 

First step: 

pi@raspberrypi:~ $ uname -a
Linux raspberrypi 5.4.79+ #1373 Mon Nov 23 13:18:15 GMT 2020 armv6l GNU/Linux

This how-to dates from 2013 and only goes up to kernel 4.19, so I may have a difficulty. 

I note that the web page that it refers to has been updated to Raspbian Buster so may be OK. But it does only have driver files up to 4.1.15 #830, which is quite a difference.

There is a script to install the drivers. It is here.

http://www.raspberrypi.org/forum/viewtopic.php?p=479340#p479340

I downloaded it, and when I ran it I got the error message:

pi@raspberrypi:~ $ sudo sh ./realtek_install.sh  
cannot match kernel: 5.4.79+ #1373
please check news at http://www.raspberrypi.org/phpBB3/viewtopic.php?p=462982
or try closest compatible version with -k <kernel build>

I tried to download the latest version listed on the website, and got the error message.

pi@raspberrypi:~ $ wget https://dl.dropboxusercontent.com/u/80256631/8188eu-20151216.tar.gz
--2020-12-23 19:01:56--  https://dl.dropboxusercontent.com/u/80256631/8188eu-20151216.tar.gz
Resolving dl.dropboxusercontent.com (dl.dropboxusercontent.com)... 162.125.64.15, 2620:100:6020:15::a27d:400f
Connecting to dl.dropboxusercontent.com (dl.dropboxusercontent.com)|162.125.64.15|:443... connected.
HTTP request sent, awaiting response... 404 Not Found
2020-12-23 19:01:56 ERROR 404: Not Found.

 so now what. 

2020-12-28 

From: https://www.raspberrypi.org/forums/viewtopic.php?f=36&t=250911&p=1786240#p1786240


ran the instructions given by Engman on Sat Dec 26, and they seem to have worked. 

pi@raspberrypi:~ $ sudo install-wifi  

*** Raspberry Pi wifi driver installer by MrEngman.
*** Performing self-update
*** Relaunching after update

*** Raspberry Pi wifi driver installer by MrEngman.

Your current kernel revision = 5.4.79+
Your current kernel build    = #1373

Checking for a wifi module to determine the driver to install.

Your wifi module is Bus 001 Device 004: ID 0bda:f179 Realtek Semiconductor Corp.  

And it uses the 8188fu driver.


Your Pi revision number is 000d
You have a Pi B v2.0
Checking for a 8188fu wifi driver module for your current kernel.
There is a driver module available for this kernel revision.
Downloading the 8188fu driver, 8188fu-5.4.79-1373.tar.gz.
Installing the 8188fu driver.

Installing driver config file rtl8188fu.conf.
mv rtl8188fu.conf /etc/modprobe.d/.
Installing driver module rtl8188fu.ko.
install -p -m 644 rtl8188fu.ko /lib/modules/5.4.79+/kernel/drivers/net/wireless
Loading and running the 8188fu driver, rtl8188fu.ko.
pi@raspberrypi:~ $

Now to reboot:

Wifi rc-car is up and running,  I am able to connect via Termius, but the MQTT-Dash doesn't seem to work. 

As the HostApd is required for my ZD1211 chipset, I am not willing to change it's parameters. 





Tuesday 1 December 2020

Debugging MQTT

I have the Raspberry Pi working with Communications from MQTT-Dash on my tablet. Now I am trying to understand it better in order to get my Wemos D1 application communicating with the R-Pi. 

The Raspberry Pi has my software which is a 'subscriber' and the 'broker' is Mosquitto' on the Pi, and I  also have Paco-MQTT on the R-Pi. MQTT-Dash is the 'publisher'.

I am using this on the R-Pi to observe the traffic received my Mosquitto:

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



Subscriber configuration:
broker_address= "192.168.4.1"
port = 1883
user = "rc-car-11"
password = "carr0t"
# 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")
------------------------------------
Broker Configuration:
Can't find any except default.

------------------------------------
Publisher Configuration: (MQTT-Dash)
Name: rc-car-pwm
username = rc-car-11  + Password
Client ID: rc-car-11c
and each button press sends one of the following: forward, slow, stop,motorleft, motorright, backwards
and the message payload that the subscriber gets is b'forward' etc.
-------------------------------------
whereas the monitor  command above sees:
forward,slow, etc. 
-------------------------------------

The Wemos configuration is at current:

const char* ssid = "rc-car";                     // Wifi SSID
const char* pswd = "Ashmeads";            // WiFi Password
const char* mqtt_server = "192.168.4.1";
const char* topic = "rc-car-11";    // this is the [root topic]
and this last I think has to change to 'rc-car-pwm'  because I had to put rc-car-11 into the monitor command above to see anything. 
----------------------------------------

Next step is to modify the Wemos software to send one of the words to the R-Pi and see what I get. 



The lines with just 'forward' or 'stop' or 'motorleft' are from MQTT-Dash,
the others are from the Wemos App.  When I remove that stuff in the Wemos app, it gives errors on compile. 

The line in the Wemos app that works is 
    client.publish( (char*) pubTopic.c_str() , (char*) payload.c_str(), true );
where pubTopic = topic  , which transmits 'rc-car-pwm' and the payload is 'forward' 

Sorted, now just a simple bit of programming to push the buttons and set the desired payload. And reduce the delay.


------------------------------------
And, back to 
https://madsmaddad.blogspot.com/2020/10/arduino-uno-wemos-d1-mini-wifi-and-mqtt.html


16-1-2021 
https://inventwithpython.com/blog/2012/04/06/stop-using-print-for-debugging-a-5-minute-quickstart-guide-to-pythons-logging-module/

adding debug statements to try and find out what is happening, but I can't find the logfile it is supposed to create.

3/2/2021  I found two Python test  programs on-line, and copied in my program, and both found the same error.

https://extendsclass.com/python.html           and
https://www.onlinegdb.com/online_python_debugger

But the program still didn't run.
There was more than one error. Now running

Help in using Logging: 
https://raspberrypi.stackexchange.com/questions/79421/logging-data-when-using-crontab

setting to use time, and to send data in the log message:

#logging.basicConfig(filename='temp.log', level=logging.INFO, 
      #format='%(asctime)s: %(message)s')
logging.info('temp: ' + str(temp) + '  |||  hum: ' + str(hum))










Wednesday 4 November 2020

Thoughts on RC Boat using Raspberry Pi and MQTT

 First off, I don't have a boat. 

Then I have done servo steering on RC-car-2  even if it is by Flask and web interface. And the servo was a step move and return after a short time.

Things that I need to know about are  how to do incremental movements of a servo AND of the throttle at the same time using MQTT. There is an app called Linear MQTT that I should look at. 

I also need to know how to pass a value across from the Publisher to the Subscriber and act on it in the incremental mode, rather  than having a different subroutine for every value. 

If I was to use a publisher other than one on my Android tablet, It couldn't use a Raspberry Pi, because that does not have an incremental input, whereas the Arduino Uno has an analog input. 

15/Feb/2021  I have been building a boat by hot-glue sticking  panels of plastic left over from my cutting up a 'square' gutter.  It floats.  I have a motor from an old RC car. It is a PEAK Motor and looks like the standard Brushed  27T motor described at rcscrapyard.net. I don't know yet whether it will run driven by PWM or not. That's a test for tomorrow. 

I have a HW-95 driver board. I have used my 3D printer to print a propeller and also a case for a 18650 Battery (ex Laptop Battery pack). 

I have a servo to use for the rudder.  Car-2 was servo steered and it looks like it used MicroSD Memory card #4.  I shall have to use that to test. It might not need much modification for the servo movement. I can take that over as Car-2 has been disposed of. 

Using the software for RC_Car-11-MQTT I have discovered that this small motor will run at varying speeds  using PWM. 

Next Iteration is to use this same software to have PWM Steering as well as motor control I think. 

And while I am about it, change the Wemos software to transmit PWM Percentages, so that I can use the Pot on the controller to adjust the steering. 





Saturday 10 October 2020

Arduino Uno, Wemos D1 Mini, WiFi and MQTT

 I have recently been given an Arduino Uno, and I already have the Wemos D1 which has Wifi. 



What I want to do as an end product is have the UNO with a number of push button switches connected, using MQTT to communicate through the Wemos Wifi to my RC car that is using MQTT. 

I think that the first step is to make the wemos into a Wifi dongle for the Arduino. 

Here are some videos to help:

https://www.youtube.com/watch?v=WnRk8w7SyTo 

This looks like a good intro to getting started with Wemos D1, but no Wifi. 

https://www.youtube.com/watch?v=q2k3CzT5qE0   -This one just a repeat, ignore it. 

https://www.youtube.com/watch?v=3bFs_MZVFxw    -Wemos wifi web server to control a relay.

Setting static IP address. More there than you think. 

https://iotbyhvm.ooo/esp8266-static-ip-address-using-arduino-example/

And another: https://www.geekstips.com/esp8266-arduino-tutorial-iot-code-example/

also: https://create.arduino.cc/projecthub/imjeffparedes/add-wifi-to-arduino-uno-663b9e



MQTT


https://www.arduino.cc/reference/en/libraries/mqtt-client/

https://www.digikey.co.uk/en/maker/blogs/2018/how-to-use-basic-mqtt-on-arduino

https://github.com/256dpi/arduino-mqtt

https://pubsubclient.knolleary.net/   *** Just a library

22/10/20

https://www.youtube.com/watch?v=NtyyfcYQxa4      and

https://github.com/martin-ger/uMQTTBroker

Observing operation via a terminal on the R-Pi:

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

FORGET THE ARDUINO

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.    [See references at end]   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/


MQTT-DASH                Wemos program

UserName=rc-car-11
+Password
Client_ID=rc-car-11c   client_Name=rc-car-11
Topic=rc-car-pwm
                                       
                                        forward,backwards etc

It's confusing.

More hints: 
https://iotdesignpro.com/projects/how-to-connect-esp8266-with-mqtt
-- testing this. 

http://bytesofgigabytes.com/mqtt/esp8266-as-mqtt-publisher-and-subscriber/

https://vimalb.github.io/IoT-ESP8266-Starter/Lesson_04/lesson.html

TESTING SCREEN

Going to try this: 
https://blog.hau.me/2018/12/26/i2c-oled-display-on-a-wemos-d1-mini/
from first test file address is 0x27
Second test file didn't do anything.
third test file (the adafruit one) caused the display to flash, so that's progress of a sort. 
This is with D1 for the clock. 
D5 for the clock didn't do anything. 

Found this: Uses 3v3 and not 5v
http://www.esp8266learning.com/wemos-mini-i2c-lcd-example.php

After  trying a number of test programs I discovered that the screen brightness was turned up full and thus no characters could be seen. 
Now have it displaying with the Emile Renaud program - the first. 
Wemos-MQTT-Test doesn't
I2C-Test-2 doesn't
I2C-Test-3 flashes screen, doesn't display words
I2C-test-4 works once I change the order of the setCursor values
    lcd.setCursor(0,2);   is position 0, line 2


As the program seems to work, but pushing the buttons doesn't do anything, I'll test the voltage to the switches and see if they need pullups. Only the stop button registers any voltage. All the others need pullups. Perhaps because all of them are at 0v is the reason why nothing can be transmitted. 

Found an IC that is 1 central pin for 12 15K resistors on other pins. Will use it for pullups for input pins. 

Interesting sites:

https://chewett.co.uk/blog/1066/pin-numbering-for-wemos-d1-mini-esp8266/

https://community.wia.io/d/49-wemos-d1-mini-esp8266-smart-iot-button-with-messagebird-sms-and-voice-messages      *** this is quite a complex example with short and long presses of a button. 

https://docs.wemos.cc/en/latest/d1/d1_mini.html

The random Nerd has a good explanation and example:
https://randomnerdtutorials.com/esp8266-nodemcu-digital-inputs-outputs-arduino/

This one tells me about INPUT_PULLUP, enabling internal pullup resistors
https://vimalb.github.io/IoT-ESP8266-Starter/Lesson_09/lesson.html


25/11/20 Lots of errors in the modified program. I tried to set the message to be transmitted (Topic) according to which button was pushed, but it doesn't like this. I think that I am going to have to specify an array of messages and then use the button press to set the key. 

That looks better, but still having trouble with the connect. 

Added Esp8266MQTTClient library by Tuan PM
EspMQTTClient by Patrick LaPointe is already installed.
adding Esp_WiFiManager by  Khoi Huang

Still have this error:
/home/peterm/wemos-Arduino/mqtt-Wemos-RC11-c/mqtt-Wemos-RC11-c.ino: 
In function 'void loop()':  mqtt-Wemos-RC11-c:62:18: error: expected primary-expression before '.' token      if (!WiFiClient.connected() && WiFi.status() == 3)
                  ^


Tomorrow, look at this:
https://gist.github.com/boverby/d391b689ce787f1713d4a409fb43a0a4

It compiles with a change of a deprecated label. 
Now set my Wifi bits in, and then add the display 

serial set to 115200
Connecting to rc-car
..........
WiFi connected
IP address: 
192.168.4.7
Attempting MQTT connection...connected
subscribed to : rc-car-11/esp-bc:dd:c2:24:b0:f4/in
Publish topic: rc-car-11/esp-bc:dd:c2:24:b0:f4/out
Publish message: {"micros":20001072,"counter":1,"client":esp-bc:dd:c2:24:b0:f4}
Publish topic: rc-car-11/esp-bc:dd:c2:24:b0:f4/out
Publish message: {"micros":40002085,"counter":2,"client":esp-bc:dd:c2:24:b0:f4}
--------
Put in LCD stuff, and moved void (setup) to beginning, but no display, though it all compiles OK. 
Put in display commands at appropriate place and it's OK.  At some places it didn't work...
Note that it is using the library ESP_WiFiManager.

Going to change it to version f, and add the pins setup.

29/11/20 
Connected to Raspberry Pi with Termius,
mosquitto_sub -h 192.168.4.1 -v -t "rc-car-11/#"  

And this is the result: 


This gives me a starting place for adding the switches. 

Note that the Rc-car is 'rc-car-pwm', but I have used on the wemos program 'rc-car-11'. This will have to change.  

Maybe that's why nothing worked on the previous revision of the wemos program- Stupid.

5/12/2020 Ok, I have the wemos sending the state 'forward' to the Raspberry Pi correctly now. 
I have now added the switch sampling software to this and got it to compile without errors. I need to reduce the 5000 msec delay and test it. Oh, first add debug messages to the display. 
Sort of works... Display flashes all sorts of random characters filling screen unti it has a message to display.   I don't think the flow of routines is quite correct. 
The serial monitor shows lots of stuff. 

It's a watchdog timer thing. 
https://github.com/esp8266/Arduino/issues/2866
or
https://forum.arduino.cc/index.php?topic=442570.0

Need to add a Yield() statement, now trying that to see where.

Adjusted timout back to 2sec from 0.5 sec.
iFi connected
IP address: 
192.168.4.7
Attempting MQTT connection...connected
subscribed to : rc-car-pwm/Wemos-ESP8266/in

--------------- CUT HERE FOR EXCEPTION DECODER ---------------

Exception (3):
epc1=0x40100961 epc2=0x00000000 epc3=0x00000000 excvaddr=0x40000150 depc=0x00000000

>>>stack>>>

ctx: cont
sp: 3ffffd80 end: 3fffffc0 offset: 0190
3fffff10:  00000001 3ffee4c4 00000001 40201720  
3fffff20:  00000000 00000c00 3ffee4c4 3ffee698  
3fffff30:  3ffee460 3ffe84cc 00000020 40100c07  
3fffff40:  3ffee460 3ffee4c4 3fffff8c 40206fde  
3fffff50:  40206fac 3ffee4c4 3fffff8c 402042e6  
3fffff60:  3ffee460 3ffee4c4 3fffff8c 402042fc  
3fffff70:  3ffee460 00000000 3fffff8c 402015e6  
3fffff80:  00000000 00000000 00000001 40100154  
3fffff90:  3fffdad0 00000000 3ffee658 40100175  
3fffffa0:  3fffdad0 00000000 3ffee658 40204adc  
3fffffb0:  feefeffe feefeffe 3ffe8514 40100ec1  
<<<stack<<<

--------------- CUT HERE FOR EXCEPTION DECODER ---------------

 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 3584, room 16 
tail 0
chksum 0xb0
csum 0xb0
v2843a5ac
~ld

Connecting to rc-car
......

Got it working by changing the code  to a do-while loop. 

Have wired it up in the case. 

Slow  (D0)      green
Right  (D3)     Orange
Stop (D4)        Red
Forward (D5)  Blue
Reverse (D6)   Yellow
Left (D7)         White
Ground            Black


Here are some pictures of the finished product. The case was an old ADSL router.




and inside:



I moved the Wemos and turned it around so that the USB connection lined up with the hole in the case just to the right of it, so that it can be powered by a USB powerbank, or updated.  The pushbuttons were cannibalized out of an old digital radio. The bits  of pcb they are attached to made it easy to hot glue them in and also to solder to.  I never connected up the battery pack. 


24/1/2021  I keep having the problem that the 'SLOW' button connected to D0 causes flickering on the display and keeps on occuring despite other buttons being pressed.  
Investigation finds that it is not a hardware problem, and here is a possible cause that needs invetigation. It looks like I can only have 5 inputs and my sixth is invalid!

https://community.blynk.cc/t/esp8266-gpio-pins-info-restrictions-and-features/22872


26/1/2021  Trying to find out the state of the subscriber on the R-Pi and why it doesn't work.

Learnt the command ps aux | grep subscriber
and the analysis of the output:
D    uninterruptible sleep (usually IO)
R    running or runnable (on run queue)       *** state desired. ***
S    interruptible sleep (waiting for an event to complete)
T    stopped, either by a job control signal or because it is being traced
W    paging (not valid since the 2.6.xx kernel)
X    dead (should never be seen)
Z    defunct ("zombie") process, terminated but not reaped by its parent
15/2/2021  If I remember correctly I got it working by taking out the timestamp from the Logging. I am just logging statements now. 





References: 
13/11/2023
https://www.ebay.co.uk/itm/295128076779










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.

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

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




Saturday 11 July 2020

Scratch, Raspberry Pi and RC-Car

Now that I have a Rspberry Pi driving an RC car via an HTML interface, my thoughts turned to wondering if I could use Scratch to drive the car.

First thoughts are how do I get scratch to interface to my GPIO pins to drive the car, and secondly whether scratch is on the tablet to do the control, or on the Raspberry Pi wih a programming interface on the tablet.

Possible links to investigate:
https://www.raspberrypi.org/blog/scratch-2-raspberry-pi/       Looks good.

https://www.raspberrypi.org/documentation/usage/scratch/     Basic, but leads to previous

It might be easier than I think.

https://www.raspberrypi.org/blog/scratch-3-desktop-for-raspbian-on-raspberry-pi/
And we are up to scratch 3 in 2019

This last suggests a simple electronics extension that could be useful.

Thursday 9 July 2020

Memory Cards, Applications and RC-Cars

This is doing my head in, so I have to get it down. I almost need a multidimensional spreadsheet.
My memory cards are numbered. The RC-car apps that I have developed are numbered, and the Cars themselves are numbered.

I did do some tests to see which cars would work with a PWM speed control, but I can't find the record of that experiment.

So CArd 4 is now in RC-Car 3
And Card 7 is in RC-car 2. Card 10 is a duplicate of card 7

Card 4:
App-py-7        PWM control of motor
                        Steering is  2 pin on/off control

App-Py-8       steering is PWM-servo
                       Motors driven by 2-pin on/off control

App-Py-PWM-Test          Motor control calculating PWM duty cycle
                       no steering

App-py.old   -> backup of py-7

CArd 7:
App-py  2-pin on/off control for both motors      Dated 2018-10-31 - An early one.
              using GPIO 18/23  and 10/11

Card 3:
App-py  2-pin on/off control for both motors      Dated 2018-10-31 - An early one.
              using GPIO 18/23  and 10/11
              with double push on forward to stop. (31-1-2019)




Friday 12 June 2020

Raspios and Duplicating Raspberry Pi system

This one is in three parts. The Third part is resorting back to Raspbian Buster to try and get this working.

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

Ok, so I have not had any luck trying to do a diskcopy from one SD card to another, so I decided to just rebuild the system.

-----------------------------         PART 2
I Installed the latest Raspbian OS, now called Raspbios, onto uSD card #10, also a 16GB card and reinstalled all the software. For whatever reason the Wifi didn't work, so I am starting again.

1. Flashed Raspbios (May'20 version) onto card and set it up to enable ssh, and also downloaded the python/HTML files into it.

2. Boot on Ethernet in R-PI card B-rev2, and update and install the driver for the ZD1211 card, and then configure the network.  [ initial IP = 26]
sudo apt-get update
sudo apt-get install firmware-zd1211
Use raspi-config to set Ethernet to 192.168.1.9/24 and wireless to 192.168.1.8/24
- this doesn't work- it cannot find wireless (dongle was not plugged in) and I don't find where to configure Ethernet.

So: edit dhcpcd.conf and wpa_supplicant.conf to configure network and wireless using the usual settings

Note that I discovered that wpa_supplicant was set to the ISSID of the downstairs router, not the local one.

Having done this, reboot and see what IP address the Ethernet picks up. Typically use fing for this.
Result - both Ethernet (9) and Wireless(8) work.


3. Install Flask and configure and get it running on wireless.
sudo apt install python3-flask

Put the shell script in Home directory and also in RC.local

File go-car.sh contains:
      export FLASK_APP=/home/pi/rc-car/app.py
      flask run --host=192.168.1.8

Tried to run it: "No module called gpiozero" error.
Found gpiozero site https://pypi.org/project/gpiozero/
It says "pip install gpiozero"
But pip command not found. 
Installation instructions:
sudo apt install python3-gpiozero
try again:
Interesting error: 
* Serving Flask app "/home/pi/rc-car/app.py"
* Environment: production
  WARNING: Do not use the development server in a production environment.
  Use a production WSGI server instead.
*** basically I can ignore it.

4. Install Access point software.
At this point follow my previous post:
https://madsmaddad.blogspot.com/2020/02/raspberry-pi-ad-hoc-wireless.html

Found that the link within it to Raspberry Pi documentation on setting up an Access Point had disappeared.
 Used  this and edited dnsmasq.conf as suggested
https://www.raspberrypi.org/documentation/configuration/wireless/access-point-routed.md
Skipped the bit about Internet Routing.

Created /etc/hostapd/hostapd.conf containing
country_code=GB
interface=wlan0
ssid=rc-car
hw_mode=g             ??? Should be b? --> g is valid for zd1211
channel=7
macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
wpa=2
wpa_passphrase=Ashmeads
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP
rsn_pairwise=CCMP

rebooted.

No wireless Lan found.
Think I'll have to edit to make hw_mode B

Changed hw_mode to b
changed channel to 4
comment out wpa_pairwise and rsn_pairwise because they were not used in normal operation.

Reboot with WiFi   -- no joy.

Check IP addresses, though this is not the problem.

Replaced Hostapd.conf with this from old version:
interface=wlan0
driver=nl80211
ssid=rc-car
hw_mode=g
channel=7
wmm_enabled=0
macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
wpa=2
wpa_passphrase=Ashmeads
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP
rsn_pairwise=CCMP

Still didn't work. The difference that I noted that made me do this is the Driver line. 

-- -- Have stuck the question up on the Raspberry Pi Forums as  # 277183

Now edited to be:

country_code=GB            # added
interface=wlan0
driver=nl80211
ssid=rc-car
hw_mode=b                  # changed from g to b
channel=4                  # changed from 7 to 4
wmm_enabled=0
macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
wpa=2
wpa_passphrase=Ashmeads
wpa_key_mgmt=WPA-PSK
# wpa_pairwise=TKIP        #commented 
# rsn_pairwise=CCMP        #commented


No luck, and it looks like the Pi has crashed? No activity light action. Plugged in Ethernet, Life.

dmesg output: 

[   20.148077] usb 1-1.2: reset high-speed USB device number 4 using dwc_otg
[   20.608179] ieee80211 phy0: Selected rate control algorithm 'minstrel_ht'
[   20.609695] zd1211rw 1-1.2:1.0: phy0
[   20.613235] usbcore: registered new interface driver zd1211rw
[   24.315134] random: crng init done
[   24.315160] random: 7 urandom warning(s) missed due to ratelimiting
[   25.769531] 8021q: 802.1Q VLAN Support v1.8
[   26.877003] Adding 102396k swap on /var/swap.  Priority:-2 extents:1 across:102396k SSFS
[   26.922096] smsc95xx 1-1.1:1.0 eth0: hardware isn't capable of remote wakeup
[   26.923339] IPv6: ADDRCONF(NETDEV_UP): eth0: link is not ready
[   27.007719] zd1211rw 1-1.2:1.0: firmware version 4725
[   27.051722] zd1211rw 1-1.2:1.0: zd1211b chip 0586:3410 v4810 high 00-19-cb AL2230_RF pa0 g--NS
[   27.105805] IPv6: ADDRCONF(NETDEV_UP): wlan0: link is not ready
[  261.167345] IPv6: ADDRCONF(NETDEV_CHANGE): eth0: link becomes ready
[  261.180014] smsc95xx 1-1.1:1.0 eth0: link up, 100Mbps, full-duplex, lpa 0x45E1
[  263.237497] ICMPv6: process `dhcpcd' is using deprecated sysctl (syscall) net.ipv6.neigh.eth0.r
etrans_time - use net.ipv6.neigh.eth0.retrans_time_ms instead



pi@raspberrypi:~ $ iwconfig
eth0      no wireless extensions.

lo        no wireless extensions.

wlan0     IEEE 802.11  ESSID:off/any
         Mode:Managed  Access Point: Not-Associated   Tx-Power=20 dBm
         Retry short limit:7   RTS thr:off   Fragment thr:off
         Power Management:off


Release notes for Raspberry Pi OS don't have anything useful. 

Tried Raspi-config to set Localisation settings (option 4) But it came back with could not communicate with wpa_supplicant



---------------------------        PART 3
Giving up on Raspberry Pi OS and going back to Raspbian Buster. If I get that working I might try a dist-upgrade on it.  So repeating the instructions as above. 

Flashing buster 2020-02-13 (looks like full system) into 16GB uSD card #10
setup ssh
edited dhcpcd.conf and wpa_supplicant.conf
added rc-car stuff

It should boot to ...9  and have updated ZD1211, and normal update on new installation procedure.
Install Flask and rc.local bit. 
This time I tried to get ahead so I tried 'pip install gpiozero' and the system responded that gpiozero is already the latest version.  OK. 

At this point reboot with wireless and check.   OK It works. 
I am connected via wireless (IP ...8) and I guess now have to install the AP stuff.

Followed instructions, and rebooted.   Wifi network not there, cannot connect.
----------------------------
Came across this:
https://github.com/raspberrypi/linux/issues/3671

It's not just my problem.

Interesting suggestions:
https://hawksites.newpaltz.edu/myerse/2018/06/08/hostapd-on-raspberry-pi
 -- This is an excellent article, even if dated 2018.


This one is out of date: ubuntu 14.04 refers
https://seravo.fi/2014/create-wireless-access-point-hostapd

Hostapd documentation, current april 2020
https://wiki.gentoo.org/wiki/Hostapd

another interesting link:
https://thepi.io/how-to-use-your-raspberry-pi-as-a-wireless-access-point/

--------------------
from this https://unix.stackexchange.com/questions/119209/hostapd-will-not-start-via-service-but-will-start-directly   I set /etc/default/hostapd line  to spell out the full file name of the hotapd config file
DAEMON_CONF="/etc/hostapd/hostapd.conf"

This is because of lines in syslog about config file not found
"Jun 18 19:44:00 raspberrypi systemd[1]: Stopped Advanced IEEE 802.11 AP and IEEE 802.1X/WPA/WPA2/EAP Authenticator.
Jun 18 19:44:00 raspberrypi systemd[1]: Starting Advanced IEEE 802.11 AP and IEEE 802.1X/WPA/WPA2/EAP Authenticator...
Jun 18 19:44:00 raspberrypi hostapd[15736]: Configuration file:
Jun 18 19:44:00 raspberrypi hostapd[15736]: Could not open configuration file '' for reading.
Jun 18 19:44:00 raspberrypi hostapd[15736]: Failed to set up interface with
Jun 18 19:44:00 raspberrypi hostapd[15736]: Failed to initialize interface
Jun 18 19:44:00 raspberrypi systemd[1]: hostapd.service: Control process exited, code=exited status=1
Jun 18 19:44:00 raspberrypi systemd[1]: Failed to start Advanced IEEE 802.11 AP and IEEE 802.1X/WPA/WPA2/EAP Authenticator.
Jun 18 19:44:00 raspberrypi systemd[1]: hostapd.service: Unit entered failed state.             
Jun 18 19:44:00 raspberrypi systemd[1]: hostapd.service: Failed with result 'exit-code'.

Brilliant, It is There!