Saturday, February 28, 2015

Pi's and Install Configuration

UPDATED:

My Raspberry Pi 2's have arrived!  Two of which are now running on the Internet.  I have three locations that I want to install and run them from.

New Raspberry Pi 2's
The initial installations will be running Raspbian (wheezy) serving simple Ham Radio Blog pages and running some HF Beaconing or Receiver code. See: http://dc01.ebcon.com:8040/

As a system administrator for large employers, I have installed and configured many Linux (UNIX) systems, I now have it down to quick trivial process.

For Raspberry Pi, First:

On the Raspberry Pi, I immediately execute the following:



$ sudo aptitude install xosview htop vnc-server vnc-viewer ssh wicd apache2 php5 tree




Note: if these are already installed, no harm. See the man pages as necessary.

Then I add users as necessary, with:



$ sudo adduser <user_name>




And then, add the appropriate admin "user_name" to the "sudo" line in /etc/group.



$ sudo vi /etc/group




Then:

There are several things I DO NOT like about most default UNIX installations.

The first is the default command "prompt", which is typically a long string of characters that is; the user and system name, and the current working directory. The information is good, but the format is terrible. While in a directory way down in the directory structure, typing space on the displayed command line is very limited, and wraps around and is difficult to use. For example, change to the directory as show:



$ cd /usr/share/SuperCollider/SCClassLibrary/Common/GUI/PlusGUI/Control/



This will result in a Command Prompt of:



pi@rbpi3 /usr/share/SuperCollider/SCClassLibrary/Common/GUI/PlusGUI/Control $ 




Note: there is little typing space on the line to the right of the "$". There is little wonder why most users get turned OFF with the Linux Command Line environment.

I personally like the same information, only in a different prompt format, for example:




/usr/share/SuperCollider/SCClassLibrary/Common/GUI/PlusGUI/Control
rbpi3$ date
Sat Feb 28 12:32:40 PST 2015

/usr/share/SuperCollider/SCClassLibrary/Common/GUI/PlusGUI/Control
rbpi3$




In this example the prompt starts with a blank line, followed by the current directory, and then on the next line, the name of the system, followed by the "$" prompt. Regardless of the length of the current directory, the user starts typing at the same location on the command line (and with space to spare).

Modifying or Adding this type of Prompt is simple, but I have done it "too" many times, I now add a simple script (/etc/bash.bashrc.local) to each system I install. I contains all of my favourite system modification. The script is as show below, details are not provided, but maybe you will find bits of it you would like also.

Note, depending on the initial OS installation, each user may want to remove the ".bashrc" and ".profile" from their home directory, or adopt parts of this script in their files. I like the system wide approach, while knowing that it is a little dictatorial.




#
# Usage in /etc/bash.bashrc
# Add the following two lines to the end of /etc/bash.bashrc, uncommenting the "test" line.

   # Start up /etc/bash_localrc for Local Stuff
   # test -f /etc/bash.bashrc.local && . /etc/bash.bashrc.local

# Local Startup files for Bash

   #echo "Start: /etc/bash.bashrc.local"
   #set -xv

   TZ='PST8PDT'; export TZ
   PATH=/usr/local/lbin:$PATH

# Show System Key

   # KEY="$(ssh-keygen -l -f /etc/ssh/ssh_host_rsa_key.pub)"
   # KEY="${KEY#* }"
   # echo
   # echo "System Key: ${KEY% *}"

# Setup the default editor
   export EDITOR='vi'
   set -o "$EDITOR"

# Setup History
   HISTSIZE=10000
   HISTCONTROL=ignoreboth:erasedups
   shopt -s cmdhist histappend lithist execfail

# Add extended globing
   shopt -s extglob

# $et the Terminal Tab value
   # If this is an xterm set the title to user@host:dir
   case "$TERM" in
   xterm*|rxvt*)
    PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME%%.*}:${PWD/#$HOME/~}\007"'
     ;;
   esac

# Prompt # for root, $ otherwise
   PS1='\n$PWD\n\h\$ '


# Local Aliases
   alias ll='ls -l '
   alias bdf='df '
   alias is='ps -ef | grep -v grep | grep -- '

   #set +xv
   #echo "End: /etc/bash.bashrc.local"


# Some Interesting Shell Stuff
   alias ralias='. $HOME/.alias'; # reread HOME aliases
   alias ...='cd ../..'
   alias ..='cd ..'

# Local GitHUB Aliases
# Git related
   alias gco='git checkout'
   alias gci='git commit'
   alias gst='git status'
   alias gbr='git branch'
   alias gls='gbr'
   alias gsbr='git show-branch'
   alias gmg='git merge --no-ff -v --progress'

   alias gad='git add'
   alias gdf='git diff'
   alias glg='git log'
   alias ggp='git grep'
   alias gpu='git push'
 
   alias gk='gitk --all &'
   alias gr='git rebase'
   alias gri='git rebase --interactive'
   alias gcp='git cherry-pick'
   #alias grm='git rm'

# End



I use "scp" to grab the script from a previously installed system.


Security Tip

If you going to put a Raspberry Pi on the Internet:
  • Remember to set a new passwd on the pi login
  • Do not open the ssh port 22 directly to the Internet, use a router to NAT and route another port to the Raspberry Pi. Note: if you DO open port 22, your system will be hammered by break-in attempts. Check your logs often.
  • Open only the ports that are necessary for your applications.

Be careful, the Internet is full of malicious hacker and "script kiddies" that will take over and eat your Raspberry Pi.

The following is a script that I wrote many years ago, as "taillogs", it "lists" and "follows" the system logs, showing new log events as they occur. I know it is somewhat cryptic, but does a nice job.

I saved this in a file: "/usr/local/lbin/taillogs".

Note: "/usr/local/lbin" is where I save all of my authored scripts.




#! /bin/sh
# Author: Eldon R. Brown, eldonb@ebcon.com

        cd /var/log &&
        find . -type f -print |
        egrep -v "\.[0-9][0-9]*$|OLD|mbox|\.offset$" |
        xargs ls -tr |
        xargs file |
        sed -n '/ text/s/:.*//p' |
        xargs tail -n2 -f

# End



With this script, it is easy to check your system logs.

--

Minima - My Coding Efforts Resumes

After a long delay (due to surgery), I am returning my attention to my Minima Controller Alternate Tuning Method coding effort.

My previous (i.e. current) revisions as available on GitHub "radiono_erb" will remain as-is, with little or no further development for now.

I will "Fork" (GitHub speak for clone) my current Minima Controller GitHub Repro and give it a new name, currently the planned name will be "radiono_PNW_Exp". This Fork will initially be used to experiment with some new Minima Controller software and hardware strategies. Later, "radiono_PNW" will be published for general use. Note: PNW denotes Controller coding efforts that some Minima Builders around the "Pacific NorthWest" are considering. See: http://groups.yahoo.com/group/pQRP/

Goals

One Goal is to reduce the front panel switch and knob foot print, that is, maybe reduce the number of switches and knobs, but at the same time increase the Controller functionality. Maybe this can be done by optimising the circuit and supporting code. The standard Minimal Volume control could be eliminated with a change of the circuit to add an I2C Quad POT. The Quad POT has four sections; 1) for volume control, the three others could be assigned other tasks, for example: 2) LCD backlight control, 3) LCD Contrast control, 4) and maybe a future Automatic Level or Gain Control (ALC or AGC). Others could be added as required or wanted.

My personal Goal is to reduce my Minima to a small hand-held unit by using very small SMT parts, yet, maintain compatibility with the majority of Builders using their Through-Hole and/or Ugly style of construction. I am a fan of Ugly Style of construction, but for my Minima project small(est) is better.

I plan to maintain circuit and software flexibility to potentially use and include a computer interface, via bluetooth or direct cable connections. Current (readily available) software programs could control and provide a familiar user environment for the Minima.

My overall Goal, which is similar to the main idea of the "Minima", is to; "Use Less Hardware, and Do More with Software".


--

Friday, February 20, 2015

Back to My Projects - Remote Desktop Protocal (RDP)

OK, it has been almost eleven weeks since my surgery - So now I can get back to; My Blog,  Electronic, Programming and Ham Radio Projects. I have been working on them, but in very short sessions.

The last few days I have been updating all of my Workstations to/with LinuxMint 17.1 (Cinnamon). I gave up on Ubuntu due to bloat and continual lack of support for problems that continued to bug me.

But LinuxMint (17.1) appears to have one of the same problems as Ubuntu - that is, Lack of "easy to use" Remote-Desktop-Protocal (RDP) configuration.

My desire is to connect and control other remote workstations and a few Raspberry Pi's from my Main Workstation. RDP is designed to display the remote Consoles on the main workstation, but people on the web have complained that after the last few system updates, it does not work as advertised, and I found that to be the case.

Disclaimer: There are many aspects of X Display, VNC and Remote Consoles that I do NOT know, nor understand. Information provided here has be found experimentally or after much online reading, your mileage may vary.

After many long hours of web research, trial and error, I now have a possible solution, which is really simple, once the magic is known. The solution is different for the remote Raspberry Pi (wheezy) than a remote LinuxMint (17.1) or newer Ubuntu system. The following examples assumes you have ssh, vnc-server and x11vnc installed as needed.

Using Remote Console of a Raspberry Pi is very easy, but several solutions are available depending on whether the Pi has a HDMI attached console or not, and whether or not there is an active logged in session.

Different methods are used to create, or use existing, Frame Buffers, and its address is denoted by the ":N" in the following examples. Any unused number can be used, but ":0" is normally reserved for the real graphic console (hardware monitor).



Pi systems "without" an HDMI attached Console (headless)

For Pi systems without an HDMI attached Console a "Display Frame Buffer" (fb) will not have been automatically created. The "vncserver" command creates a virtual Frame Buffer ":2", as seen in the following example. Also, note: ":2" is an alias for the value of the last two digits of "port number 5902".

Execute the following on the local system:

$ ssh remote_pi_sys_address 'vncserver -geometry 900x600 :2'
$ vncviewer remote_pi_sys_address:2

Note: the Geometry can be any size you like, I like 900x600 because it does not completely fill my local display.

Remote Virtual Console
Enjoy remote access to the PI, if the local window is deleted, it can be re-entered by re-executing the second command.



Pi systems "with" an HDMI attached Console, with Active Session

On remote system, run "Share Desktop", then on the local system execute:

$ vncviewer remote_pi_sys_address:0



Or, Pi systems "with" an HDMI attached Console, with Active Session

$ ssh -xCf -L 5900:localhost:5900 remote_pi_sys_address -l root \
        'x11vnc -q -auth /var/run/lightdm/root/:0 -display :0 -N'

$ vncviewer :0

Note: The required "-auth /var/lib/mdm/:0.Xauth" parameter is dependent on your remote_system and display manager used, which normally can be found via a remote "ps -efl | grep auth" command.



LinuxMint, Ubuntu and other Debian derived systems with RDP and VNC Console bugs.

See the Note above, regarding "auth". The following is accessing a remote LinuxMint system at the login prompt, supplying user name and passwd starts a normal remote session. Note: the displayed window will be the size and resolution of the remote monitor, scrolling may be necessary.

$ ssh -xCf -L 5900:localhost:5900 remote_sys_address -l root \
        'x11vnc -q -auth /var/lib/mdm/:0.Xauth -display :0 -N'

$ vncviewer :0

Remote Login
Note: failure can occur if the Local and Remote ports (5900) (as being requested here) are already in use, some of the following commands can be executed on the Local and Remote systems to help find port collision problem, killing the offending processes will free the port.

$ netstat -ta
$ lsof | grep 5900
$ ps -efl | grep 5900
$ ps -efl | grep vnc

The use of a "virtual" Console would be much better, one that allows you to specify the window size. But alas, it does not work as expected, the default configuration does NOT provide an interactive window manager.

This example does not work as well as it should.

$ ssh -xCf -L 5908:localhost:5908 remote_sys_address \
        'vncserver -geometry 900x600 :8'

$ vncviewer :8

I plan to continue to explore for a usable solution that provides a specified size of window for LinuxMint, Ubuntu and other Debian Derived systems. Currntly only the Raspberry Pi (wheezy) works as expected.


--

Wednesday, November 5, 2014

Confession of Arrogants

This is a confession of an Arrogant Engineer.

I may not be posting much more to this blog for a while. Although, I will still be thinking of electronic projects and software solutions for interesting problems. But, . . . most of my attentions will be elsewhere.

For the last few weeks (months) I have been feeling weak, it was getting difficult to climb the 32 steps to my Loft Apartment. I am 68, and I was just thinking I am getting older. But then, when going down the stairs was getting difficult, I decided something was wrong and decided it was time to see my Doctor again.

After some blood test, they found low-red-cell-count and low-Iron. Iron is necessary to make more NEW red blood cells. The Doctor suspected I was leaking blood into my intestines and iron was being depleted trying to replace lost blood. Note: Normally it takes about 90 days to replace your own blood.

My Arrogance

Two years ago, I ignored my Doctors advice to get a Colonoscopy. For those that do not know, the Colon is the name for the entire Large Intestine.

A colonoscopy is the process of viewing the colon from the inside. It sounds terrible, but completely painless with drugs. Unfortunately, there is several days of prep which requires you to drink some awful tasting clear liquid the day before.

To make a long story short; Last Monday my colonoscopy found a "growth" within my Colon that is leaking blood. Even without the pathology test, it is suspect to be Cancer. The good news is it appears to be only associated with one short section of my colon, maybe 6cm (2 inches). Hopefully, a resection of my colon will remove it all. I have appointments later this week for review and surgery planning.

If my problem would have been found earlier, it would have been a simple in-office procedure to remove a polyp or two. That was done from another location during my current colonoscopy.

My advice, Hobbyist-to-Hobbyist, Engineer-to-Engineer;

Get a Colonoscopy as soon as your Doctor recommends.

I am planning a New Blog to posts my colon adventures, I know it will not be as interesting as Ham Radio and Electronic Projects, but it is what I can do to encourage others to follow Doctors orders, I will edit here and add the URL when it is established. And of course, as usual, I will try to provide clinical photos and details.


--

Wednesday, October 29, 2014

Minima - User Options


On Mon, Oct 27, 2014 at 11:36 AM, John <****@*******> wrote:
Hello Eldon
I know that you said that you want to stop coding and get on with construction,  I was just about to upload BS02 again but with various options turned off to suit my way of operating , which is a bind, as I have to make the changes, upload again every time I make a small change,     So I was wondering if it would be possible to have some of the more popular options available on the menu like you have the 60m (yes /No), possibly     Tune 2500 khz,    CW beacon,    Scanning, they could all be Yes/No options
Would save a lot of trouble,   Just a suggestion !!!! get the minims going first
73
John


John,

I decide to respond to your questions via a blog post, and CC to the Minima email reflector, so my answers can be leverage by others.

Yes, I need to finish my Minima build.

And YES, most options could (or should) be added to the menu option.

Although, I wrote the menus as it is, in hast, as a trial to see if it was valuable. In hast, means that the menu system is very inefficient and requires much code space than it should. It needs to be rewritten with space, performance, and optimisation in mind.

In previous revisions of the Arduino IDE, my Minima Alternate Tuning Method (MATM) Sketch was running out of space and therefore user compile-time USER_OPTIONS was the only method available for allowing users to pick and choose their desired functions. As you know, with the NEWER Arduino IDE 1.5.8, the MATM uses much less of the available space and therefore most (if not all) current USER_OPTIONS will fit, at the same time.

John, I think you have said that you take your ATMEGA328P processor out of the Minima circuit and place it in an Arduino UNO to reprogram it. If so, yes, I can see how compile and modifications would be a pain - and therefore menus would be much better. First, I suggest that you upgrade and use a USB to Serial Converter connected to a four pin header on the edge of your controller board. There are NO components necessary to use this header. Although personally, I always put a 1nF cap on all processor pins that leave the processor board, especially when used in an RF environment. Downloading a Sketch and Restating the processor with this set up is automatic.

PropPlug and Four Pin Header
There are several USB-to-Serial Converters available from different manufactures, most are created using the same FTDI FT232R chip.  I use the "PropPlug" from Parallax. The required four header pins from the processor are; GND, TX, RX, and Reset. The PropPlug works very nicely with the Arduino IDE.

As most readers of my blog know, I like to build electronic project with the smallest parts that I can find (small is my thing). For example, for the Minima I did not use the ATMEGA328P-PU, I used the ATMEGA328P-MU which is a small MLF-32 package. The downside is, it can not be taken out of the circuit to be programmed, nor can it be easily replaced.

Top: ATMEGA328P-PU
Bottom: ATMEGA328P-MU

For me, using the original suggested large DB9 Serial connector for programming on the back of my project was a non-starter, but a simple four pin header is acceptable. Also, the original suggested level translation parts are not necessary with a FTDI interface.


So Yes, new revisions of my MATM software will include more menu items to make option selection easier. Note: "menus" will always be a compile time USER Option.


--

Sunday, October 26, 2014

Julian - G4ILO

This weekend I learned of the loss of my friend and fellow blogger, Julian Moss - G4ILO.
Julian Moss - G4ILO
Julian has succumb to an incurable brain tumour, which he gallantly fought, and has blogged about at: http://onefootingrave.blogspot.com/ . Like most, I will miss him and his Ham Radio Blog entries at: http://blog.g4ilo.com/

My blog is a direct result of Julian's encouragement, he convinced me to start my own blog. He encouraged and guided my initial efforts. Over the years, we exchanged posts, comments, email, programs, and even some small QRP hardware projects.
 
So, I think, A blog entry is the best possible tribute to my friend - Julian.

RIP - Julian - G4ILO, you will be missed.

--

Monday, October 20, 2014

Minima - Jeff's ENCODER04

This is a proposed configuration to support Jeff's ENCODER04 routines within my Minima's Alternate Tuning Method. This is a fantastic addition for the Minima.



The following circuit should be added to the Minima to implement the ENCODER04 Rotary

Encoder and Multiple Push-Button Switches parallel to the original FN Switch. 

--------+
Arduino |
        |
   AVCC |
   pin20|--------+---1K---- +5V
        |        |
        |        = 100nF
        |        |
        |        G
        |
    PD5 |---------------- To Original Minima LowPass Filter
  pin11 |
        |
    PC0 |---------------- To Proposed Rf386 Power Amp Filter Selector
  pin23 |
        |
        |
    PD7 |                                    +--------+
  pin13 |------------------------+-----------|B      C|------------------------+
        |                        |     G-----|G  ENC  |                        |
    PD6 |--------------+---------)-----------|A      G|---+                    |
  pin12 |              |         |           +--------+   |                    |
        |              = 1nF*    = 1nF*                   G                    |
        |              |         |                                             |
        |              G         G                                             |
   AREF |                                                                      |
   pin21|----+-------+                       * = Optional but Suggested        |
        |    |       |                           for CPU's in RF Environments  |
        |    |       = 100nF                                                   |
        |    |       |                                                         |
        |    |       G                                                         |
        |   47K                                                                |
        |    |                                                                 |
        |    |                                                                 |
        |    |                                                                 |
    PC3 |    |                                                                 |
   pin26|----+-----+---4K7---+---4K7---+---4K7---+---4K7---+---4K7---+---4K7---+
        |    |     |         |         |         |         |         |         |
        |   FNS    = 1nF*    S         S         S         S         S         S
   AGND |    |     |         |         |         |         |         |         |
   pin22|----+-----+---------+---------+---------+---------+---------+---------+
        |    |
--------+    G

            "FN"           "Left"   "Right"   "SBand"     "Up"     "Down"     btn7
           (btn1)          (btn2)    (btn3)   (btn4)     (btn5)    (btn6)    (btn7)


Where:
  4K7 is a 4.7K ohm resistor
  47K is a 47K ohm resistor
  FNS is the original FN switch
    S is a new switch
    = is a capacitor
    G is a ground and AGND
  ENC is the Rotary Encoder (A/G/B) with Push Button (C/G).

NOte: The Encoder Push Button switch (pins C/G) is parallel with btn7, if desired,
      one or the other switches can be deleted of left in parallel.

Note: The Encoder pins A and B, can be exchanged to reverse the Encoders electrical rotation.


ENCODER04 is available as a User Option within the current Rev (ERB_IL) of Minima Alternate Tuning Method at:


--

Thursday, October 16, 2014

Minima - Encoder, Two Implementions

After several days of work, I think I now have a working set of Encoder Routines that are usable for the Minima. Testing has been done by several builders.

The first routine: Encoder01, uses a polling analog read (non interrupt) to detect the Encoder switch changes and is not listed below.

The second routine; Encoder02, is usable for the builders that have moved to an I2C LCD and therefore have two dedicated microprocessor pins to connect to the Encoder pins A and B.

The third routine; Encoder03, is usable for builders that continue to use the parallel LCD and therefore do NOT have dedicated pins to connect to the Encoder. The previous Analog Tuning Pin and the FN Pin are used as shown in the suggested multi-switch schematic.

Selecting which Encoder routines are used, is done via a Optional Configuration selection in the "A1Config.h" file, by un-commenting the selected Encoder.



//#define USE_POT_KNOB  1 // 2304b - Option to include POT support
//#define USE_ENCODER01 1 // 2220b - Option to include Simple Encoder01 support
//#define USE_ENCODER02 1 // 2610b - Option to include FULL Two Digital Pin ISR Encoder02 support
  #define USE_ENCODER03 1 // 2604b - Option to include ISR Encoder03 support On Tuning Pin


Now that the details are work out, the Encoder supporting routines are short and simple. Each containing the "tigger" debounce timers as suggested by the author of the PinChange Library. Yes, it is called "tigger", because everyone knows tiggers bounce, as in Winnie-the-Pooh.

Some unnecessary detail are left out of these listing, check the GitHub for the actual code.

For Encoder02, these routines are used:



#include "PinChangeInt.h"

volatile int knob;

// ###############################################################################
void encoderISR() {
    int pin = ENC_B_PIN;
    static unsigned long startTime = 0;
    unsigned long tigermillis;
    uint8_t oldSREG = SREG;

    cli();
    tigermillis = millis();
    SREG = oldSREG; 
    if (tigermillis-startTime <= ISR_DEBOUNCE_TIMEOUT) return;
    startTime=tigermillis;
    
    knob += digitalRead(ENC_B_PIN) ? -1 : +1;
}

// ###############################################################################
void initEncoder() {
    int pin = ENC_A_PIN;
     
    pinMode(ENC_A_PIN, INPUT_PULLUP);
    pinMode(ENC_B_PIN, INPUT_PULLUP);
    
    PCintPort::attachInterrupt(pin, &encoderISR, FALLING);
}

// ###############################################################################
int getEncoderDir() {
    char tmp = knob;
      
    if (tmp>0) {uint8_t oldSREG = SREG; cli(); knob--; SREG = oldSREG; return +1;}      
    if (tmp<0) {uint8_t oldSREG = SREG; cli(); knob++; SREG = oldSREG; return -1;}
    return 0;
}


For Encoder03, these routines are used:



#include "PinChangeInt.h"

volatile char knob;

// ###############################################################################
void encoderISR() {
    int pin = ENC_B_PIN;

    static unsigned long startTime = 0;
    unsigned long tigermillis;  
    uint8_t oldSREG = SREG;

    cli();
    tigermillis = millis();
    SREG = oldSREG;   
    if (tigermillis-startTime <= ISR_DEBOUNCE_TIMEOUT) return;
    startTime=tigermillis;
        
    knob += analogRead(pin) < 440 ? -1 : +1;
}

// ###############################################################################
void initEncoder() {
    int pin = ENC_A_PIN;
      
    pinMode(ENC_A_PIN, INPUT_PULLUP);

    PCintPort::attachInterrupt(pin, &encoderISR, FALLING);
}

// ###############################################################################
int getEncoderDir() {
    char tmp = knob;

    if (tmp>0) {uint8_t oldSREG = SREG; cli(); knob--; SREG = oldSREG; return +1;}
    if (tmp<0) {uint8_t oldSREG = SREG; cli(); knob++; SREG = oldSREG; return -1;}
    return 0;
}


Notice: Only a few lines are different between the two implementations.

--

Tuesday, September 30, 2014

Minima - Multi-Button Funciton

In previous revisions of my Minima Controller Code, I had used a "table" to lookup and decode the Buttons being pressed.

The buttons are connected together via  identical resistors to form a resistive ladder (see previous post). It was a simple matter of pressing a button, reading the resulting decoded value at the analog port of the ATMEGA328, and then inserting the correct value in the table for that button (Note: some of the current coding details have been left out, see source if necessary).



// ###############################################################################
int btnDown(){
  int val;
  
  val = analogRead(FN_PIN);

  if (val>1000) return 0;
 
  // 47K Pull-up, and 4.7K switch resistors,
  // Val should be approximately = 1024*btnN*4700/(47000+(btnN*4700))
  // N = 0 to Number_of_button - 1

  if (val > 350) return 7;
  if (val > 300) return 6;
  if (val > 250) return 5;
  if (val > 200) return 4;
  if (val > 150) return 3;
  if (val >  50) return 2;
  return 1;

}




That became a little boring, so I decided to replace the table with an algorithm.




// ###############################################################################
int btnDown(){
  int val = 0;

  val = analogRead(FN_PIN);

  if (val>1000) return 0;

  // 47K Pull-up, and 4.7K switch resistors,
  // Val should be approximately = 1024*btnN*4700/(47000+(btnN*4700))
  // N = 0 to Number_of_button - 1

  // 1024L*b*4700L/(47000L+(b*4700L))   >>>  1024*b/(10+b);

  for(int b = MAX_BUTTONS - 1; b >= 0; b--) {
      if(val + 15 > 1024*b/(10+b)) return b+1;
  }
  return 1;
}




The NEW algorithm is smaller, faster and more flexible than the "table", only MAX_BUTTONS need to be change to add/remove new buttons. There is probably a limit to the number of buttons that can reasonably be added to the Resistive/Switch chain, currently I have used eight.

Note: According to ohm's law, with 47K ohm Bias Resistor and 4.7K ohm Switch Resistors, (see previous post) the value read by the ATMEGA should be:

val = 1024 * b * 4700 / (47000 + (b * 4700)); 
 
Where "b" is the button pressed

As long as the Bias and Switch Resistors have a fixed ratio (in this case 10:1), they can be factored-out to leave a much smaller function:

val = 1024 * b / (10 + b);

The biggest disadvantage of using an algorithm is; it can NOT easily be tweaked to solve a resistive tolerance problems - the moral of the story, use good resistors and pay attention to the Bias source for the network and the ATMEGA contained ADC's.

--

Saturday, September 27, 2014

Minima - Proposed Rotary Encoder Circuit

This is just a proposal, the final suggested circuit maybe somewhat different, this is a excerpt, with additions, from a previous post.

My current experimental Encoder software works very smooth with this circuit. Whit a little more testing, it will be published on GitHub soon.

My goal is to be as compatible with the Original Minima as possible.


The following circuit should be added to the Minima to implement a Rotary Encoder and
Multiple Push-Button Switches parallel to the original FN Switch. The original
Tuning POT has been removed to accommodate the Encoder.

--------+
Arduino |
        |
   AVCC |
   pin20|--------+---1K---- +5V
        |        |                       +--------4K7-----+
        |        = 100nF                 |                |
        |        |                       |   +--------+   |
        |        G                       +---|B      C|---+--------------------+
 Tune A2|                              G-----|G  ENC  |                        |
   pin25|--------+---------------------------|A      G|---+                    |
        |        |                           +--------+   |                    |
        |        = 1nF                                    G                    |
        |        |                                                             |
        |        G                                                             |
   AREF |                                                                      |
   pin21|----+-------+                                                         |
        |    |       |                                                         |
        |    |       = 100nF                                                   |
        |    |       |                                                         |
        |    |       G                                                         |
        |   47K                                                                |
        |    |                                                                 |
        |    |                                                                 |
        |    |                                                                 |
    PC3 |    |                                                                 |
   pin26|----+-----+---4K7---+---4K7---+---4K7---+---4K7---+---4K7---+---4K7---+
        |    |     |         |         |         |         |         |         |
        |   FNS    = 1nF     S         S         S         S         S         S
   AGND |    |     |         |         |         |         |         |         |
   pin22|----+-----+---------+---------+---------+---------+---------+---------+
        |    |
--------+    G

            "FN"           "Left"   "Right"   "SBand"     "Up"     "Down"     btn7
           (btn1)          (btn2)    (btn3)   (btn4)     (btn5)    (btn6)    (btn7)


Where:
  4K7 is a 4.7K ohm resistor
  47K is a 47K ohm resistor
  FNS is the original FN switch
    S is a new switch
    = is a capacitor
    G is a ground and AGND
  ENC is the Rotary Encoder with Push Button

Note: The Encoder pins A and B, can be exchanged to reverse the Encoders electrical rotation.

-


More info to follow.

--