Thursday, September 29, 2016

Raspberry Pi & Arch Linux - Day 7 - Stepper Motor




Today, we made significant progress: we set up the rotational radar mentioned in the structure last time.

The basic components of the rotational radar are:




























To connect them together, we will need some LEGO bricks. The final structure looks like this:














Before we move forward, we have to have some basic understanding of the stepper motors. There are very good documentations and posts online, here is a list of them:


With the driver board, wiring is very easy. Just keep in mind that the motor and the raspberry should share the same Ground. The raspberry pi 5V pin should be able to driver the motor without any issues. If your motor vibrates but not spins, you may check:

  • the setting of speed is not too fast or too slow. If the speed is set too high, the motor will fall behind the control signal; if the speed is set too low, then movement of the motor is not visible.
  • the step sequences are wrong.

The notion of speed (step angle, revolution) and step sequences can be found in the linked above. The speed is controlled by setting the delay between to two output signals.

I attached my code here. If you want to use the code, make sure you update the pin number.



import RPi.GPIO as gpio
import time

gpio.setmode(gpio.BOARD)


in_1 = 3
in_2 = 5
in_3 = 7
in_4 = 11


# set all motor input to 0
gpio.setup(in_1, gpio.OUT, initial=0)
gpio.setup(in_2, gpio.OUT, initial=0)
gpio.setup(in_3, gpio.OUT, initial=0)
gpio.setup(in_4, gpio.OUT, initial=0)


time.sleep(1.5)


def rotate(pins, degree=None, clockwise=False, delay=0.002):
    if clockwise:
        in_1, in_2, in_3, in_4 = pins[::-1]
    else:
        in_1, in_2, in_3, in_4 = pins

    if degree is None:
        remaining = 1
    else:
        remaining = degree
    
    print(in_1,in_2,in_3,in_4)

    stepsize = 360. / 4096.  * 8
    while degree is None or remaining > 0:
        print('remaining: {}'.format(remaining))
        gpio.output(in_1, 1); time.sleep(delay); 
        gpio.output(in_4, 0); time.sleep(delay); 
        gpio.output(in_2, 1); time.sleep(delay); 
        gpio.output(in_1, 0); time.sleep(delay); 
        gpio.output(in_3, 1); time.sleep(delay); 
        gpio.output(in_2, 0); time.sleep(delay); 
        gpio.output(in_4, 1); time.sleep(delay); 
        gpio.output(in_3, 0); time.sleep(delay); 
        remaining -= stepsize

def swing(pins, degree=180, delay=0.002):
    while True:
        rotate(pins, degree=degree, clockwise=True,delay=delay)
        for pin in pins:
            gpio.output(pin,0)
        time.sleep(3 * delay)
        rotate(pins, degree=degree, clockwise=False,delay=delay)
        for pin in pins:
            gpio.output(pin,0)
        time.sleep(3 * delay)

if __name__ == '__main__':
    print("starat")
    time.sleep(2)
    pins = [in_1, in_2, in_3, in_4 ]
    #rotate([in_1, in_2, in_3, in_4], degree=360)
    swing(pins, degree=180)
    


Here is the video:



The next step is to connect the distance sensor to raspberry pi and write code to process the data.



Tuesday, September 27, 2016

Raspberry Pi & Arch Linux - Day 6 - set up Git and create repository remotely




Problem 6: How to set up git environment

First, we need to install git. It is straightforward with pacman. What we want to focus today is how to initiate a repository using command line. this is a good place for a quick start with git.

Here is a extract from the Pro Git Book
1. configure git
$ git config --global user.name "John Doe"
$ git config --global user.email johndoe@example.com
2. initiate the directory of interest
$ git init
3. add files and commit
$ git add *.c
$ git add LICENSE
$ git commit -m 'initial project version'

What we miss here is to create a repository remotely through command line. Of course, we can login our git account and create it manually but we want to stay with arch linux.

To create repository remotely, we need to refer to Git API. Here we give one working solution.

$ curl -u 'username' https://api.github.com/user/repos -d '{"name": "ProjectAutoCar", "description": "Project to build a auto car using Raspberry Pi"}'
$ git remote add origin https://github.com/meretciel/ProjectAutoCar.git

"proejctAutoCar" is the name of the repository. Now everything is ready and we can push the project to Github.
$ git push origin master


The ProjectAutoCar is what we want to do with Raspberry PI. We want to see if we can use Raspberry Pi to build a small auto-pilot car. It would be a great learning opportunity to have a better understanding of electronic components and basic machine learning algorithms.


We outline the basic structure (draft version) here and we will make changes as we get into details later.





Monday, September 19, 2016

Raspberry Pi & Arch Linux - Day 5 - install numpy and scipy on Arch Linux


Problem 6: How to install numpy and scipy on ArchLinux

Raspberry Pi has a powerful device: GPIO. To play with it, the first thing to do is to install python and RPI.GPOI to arch linux. It turned out to be tricker than I thought to get python and related packages installed.

To install python is straightforward:

pacman -S python

This will download python3. It is good to start moving to python3 because the official support will end in 2020.

It is convenient to have a python package manager on board. So we install pip:

pacman -S pip

At the time of this writing, pacman is unable to install anaconda, which is the package manager I like the most. On ArchLinux Wiki, it says the url/link is outdated.

Once we have pip, it is straightforward to install RPI.GPIO

pip install rpi.gpio

The next step is to install some common-used libraries, such as numpy and scipy. I tried to use pip and easy_install to install them. However it took too much time to complete that I needed to stop the process. It seems that it is not recommended to install numpy ans scipy via pip in Linux machine because the it actually downloads the package and compile it locally. And this may be the reason why when I tried to install numpy using pip I got compiling error (saying that fortran compiler is missing etc...).

The alternative is to use pacman:

pacman -S python-numpy python-scipy

We also install openCV in case we need to do some image processing later when I receive the camera:)

pacman -S opencv

Saturday, September 17, 2016

Raspberry Pi & Arch Linux - Day 4 - How to change the default value of From in the mail command



We start wit the follow-up about mail commend.

Problem 4: How to change the default value of From in the mail command

As we noticed last time, when we use the mail command to send emails to our personal account, the From field is set to root by default. One way to change the default value is to use the -r option

The man page of mail gives us:


Here is a concrete example:

echo "test" | mail -s "test" -r "sender-name <sender@gmail.com>" receiver@gmail.com


Problem 5: How to connect to Raspberry Pi from Mac

In order to make writing more efficient, it is better to have access to Raspberry Pi through Mac. There are two benefits: (1) now I can use only one keyboard (2) I have all the nice functionality in Mac. The most important one is to make screenshot. As I am using command line mode in arch linux, it is hard to me to make screenshot without GUI (X windows something). It seems even impossible to me to make a screenshot under this circumstance. Maybe I need to do some more researches online.

To connect to my Raspberry PI, I choose to use ssh. Just type

ssh username@ip-address

And then enter your password. Very simple. Again, to find the ip information, use ifconfig  command.







Monday, September 12, 2016

Raspberry Pi & Arch Linux - Day 3

Raspberry Pi & Arch Linux - Day 3

In this brief post, we will describe how to send email in Arch. 

There are several choices to send email in linux. To get things done quickly, I choose the one that looks the simplest: SSMTP.

Problem 3: How to send an email with SSMTP

If the ssmtp tool is not installed on the system, type pacman -S package-name to install it. On my Arch Linux, the ssmtp is not pre-installed.

After the installation, we need to edit the configuration file in /etc/ssmtp/ssmtp.conf. The configuration is straightforward and the options are self-explanatory.

Here is the sample configuration file copied from the Arch Wiki:

/etc/ssmtp/ssmtp.conf
# The user that gets all the mails (UID < 1000, usually the admin)
root=username@gmail.com

# The mail server (where the mail is sent to), both port 465 or 587 should be acceptable
# See also https://support.google.com/mail/answer/78799
mailhub=smtp.gmail.com:587

# The address where the mail appears to come from for user authentication.
rewriteDomain=gmail.com

# The full hostname
hostname=localhost

# Use SSL/TLS before starting negotiation
UseTLS=Yes
UseSTARTTLS=Yes

# Username/Password
AuthUser=username
AuthPass=password

# Email 'From header's can override the default domain?
FromLineOverride=yes

To send an email, use the following command:

$ echo test | mail -v -s "testing ssmtp setup" tousername@somedomain.com

There is one critical issue with this approach: the security.  Note that the configuration contains the email username and password. It is not safe to keep your personal profile in this way. The Arch Wiki page suggests creating a new ssmtp group and set the ownership. The security problem would be my next topic but for today at least we can send the email.

Trick

As a beginner to the linux system, I am not familiar with all the commands. I often store some commands in a text file. Some commands are really long and it is not convenient to type the code every time. Here is a command that select a specific line in the file and execute it.

$ cat my-command-file | awk "NR==line-of-interest{print}" | bash

The first part of the command is just to print out the whole file; the second part is to select the line of interest and then finally pass it to bash. The bash command will execute the string command coming out of awk tool.


Sunday, September 11, 2016

Raspberry Pi & Arch Linux - Day 2


Raspberry Pi & Arch Linux - Day 2


Today's objective is to set up the automatic wifi connection. Again, the Arch Linux Wiki has everything, just follow the instruction and we will be fine. (https://wiki.archlinux.org/index.php/Netctl)

We will manage the wifi connection with the netctl tool. Instead of typing all the commands mentioned in Day 1, we can store the wifi connection configuration in a profile file. The profile file should be in /etc/netctl. As mentioned in the wiki, we can copy the sample profiles in the /etc/netctl/example folder and make appropriate customization.

Here is an example of the profile file: 

[To be added]


To establish a connection, just enter the following the commend:

netctl start profile

If the command fails, type netctl status profile to see the error message. Note that before running netctl make sure that there is no other network service running in the background. In our case, we need to first disable the wifi connection

ip link set wlan0 down


Now everything should work!

At this point, I need to find a solution to copy the message from Raspberry Pi to Mac. It becomes painful to re-type the output messages of Raspberry Pi.  Obviously it is not the right time to start writing blog on Raspberry directly. I haven't even try google on Raspberry. The best way I can think of is to send email from Raspberry Pi to my personal email.

TODO:

  1. learn how to send email.








Saturday, September 10, 2016

Raspberry Pi & Arch Linux - Day 1


Raspberry Pi & Arch Linux - Day 1

Today is the start of a new journey: learn linux system.

Past experience has taught me that doing experiment with linux on PC is too risky. At first I was thinking of getting a cheap used computer and install a linux system but this is still expensive. After some researches on the internet, the Raspberry Pi caught my attention. It is a mini computer that costs only $50. I am not sure if it is a powerful machine but obviously it is enough for me to learn the linux system. (For more information, please refer to https://www.raspberrypi.org)

The next question is which linux distribution to use. I have Ubuntu on my personal computer. Some people recommend to start with Ubuntu but I want something more challenging. Ubuntu is user-friendly precisely because it has everything pre-installed. In order to learn the linux, I believe it is better to build something on my own. This thought makes me finally chose the Arch Linux distribution which is a lightweight and flexible linux distribution. (For more information about Arch Linux, please refer to https://www.archlinux.org)


The first thing to do is to start the Raspberry Pi. I bought my Raspberry Pi from Amazon:

(https://www.amazon.com/CanaKit-Raspberry-Clear-Power-Supply/dp/B01C6EQNNK/ref=sr_1_6?s=pc&ie=UTF8&qid=1473563202&sr=1-6&keywords=raspberry+pi+3)

This product does not include the SD card and unexpectedly this makes the very first trouble.

Problem 1 : SD Card

For some reasons, I wanted to have a large SD card. I was thinking the larger the SD card is the better because SD card is used as a disk for the Raspberry Pi. I bought a 64G SD card but it turns out to be the first "mistake".

64G SD card uses a special filesystem: extFAT. According to Wikipedia:
exFAT is a proprietary and patent-protected file system with certain advantages over NTFS with regard to file system overhead.
exFAT is not backward compatible with FAT file systems such as FAT12, FAT16 or FAT32. The file system is supported with newer Windows systems, such as Windows Server 2003, Windows Vista, Windows 2008, Windows 7, Windows 8, and more recently, support has been added for Windows XP.[27]
exFAT is supported in OS X starting with version 10.6.5 (Snow Leopard).[26] Support in other operating systems is sparse since Microsoft has not published the specifications of the file system and implementing support for exFAT requires a license. exFAT is the only file system that is fully supported on both OS X and Windows that can hold files bigger than 4 GB.[citation needed]

Having no idea about these details, I tried to write the Arch Linux image file to SD card on a Linux machine but always got a permission error. I cannot even format the SD card on my linux machine and now I kind of understand this is a filesystem format issue. I did try to format the SD card on Mac but I chose the MS-DOS(FAT) which seems to make the situation worse.

After several attempts to write Arch Linux to the SD card, I finally gave up. At this point it is too difficult for me to solve this format problem. Once I format the SD card on Mac, it seems impossible for me to re-format on a Linux machine not to mention writing the image file to the SD card. The only choice is to buy a new SD card. This time I bought a 16G SD card and hopefully it can work.

(SanDisk Ultra 16GB Ultra Micro SDHC UHS-I/Class 10 Card with Adapter (SDSQUNC-016G-GN6MA, https://www.amazon.com/gp/product/B010Q57SEE/ref=oh_aui_detailpage_o01_s00?ie=UTF8&psc=1)

Following the instruction again (https://archlinuxarm.org/platforms/armv8/broadcom/raspberry-pi-3) and now everything works smoothly.




Now I can start the Arch Linux on my little Raspberry Pi, which is good and makes me excited, but soon I realize one important thing: Arch Linux is so simple that it has nothing! There is no GUI and everything is in command line. Interesting...

To play with Arch Linux, I need a real computer so that I can search useful information. This is a little bit annoying because I need to switch between to keyboards. So the next step is to get internet connection.



Problem 2: How to connect to Wifi

It turns out the Arch Linux Wiki has everything I need if I do not skip any sections on the page and strictly follow the instruction.(https://wiki.archlinux.org/index.php/Wireless_network_configuration#Getting_an_IP_address)

Here are the steps to connect to wifi:

  1. set up the wlan0 interface: ip link set wlan0 up
  2. connect to wifi: wpa_supplicant -B -D nl80211,wext -i wlan0 -c <(wpa_passphrase "your_SSID" "your_key"). wpa_supplicatn can run in the background. After entering this command, press ctrl+c to exit.
  3. getting an IP address: dhcpcd wlan0 
  4. (done.)


TODO list:
  1. how to automatically config the wireless connection?
  2. can we save the configuration/profile?
  3. [research] Filesystem
  4. [research] SD card
  5. [research] WPA/WPA2, WEP










Saturday, September 3, 2016

LeetCode: 386. Lexicographical Numbers

386. Lexicographical Numbers  QuestionEditorial Solution  My Submissions
Total Accepted: 4021
Total Submissions: 12734
Difficulty: Medium
Given an integer n, return 1 - n in lexicographical order.

For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9].

Please optimize your algorithm to use less time and space. The input size may be as large as 5,000,000.



class Solution {
public:

    vector<int> lexicalOrder(int n) {
        vector<int> res;
        
        int candidate = 1;
        int count = 0;
        
        while (count < n) {
            res.push_back(candidate);
            ++count;
            if (10 * candidate <= n) {
                candidate *= 10;
            } else if (candidate + 1 <= n) {
                candidate++;
                while (candidate % 10 == 0) candidate = candidate / 10;
            } else {
                candidate = candidate / 10;
                while ((candidate + 1) % 10 == 0) candidate = candidate / 10;
                ++candidate;
            }
        }
        return res;
    }
};