Try debugging Python on Raspberry Pi with Visual Studio.

So that you can make Python as easily as possible

Both Raspberry Pi and Python have just started, and it's quite tough. So, I tried it from the earnest desire to debug Python on Visual Studio. Somehow, I feel like I can go. I don't think the hurdles for preparing the environment are high, so why not give it a try?

Target

I want to reduce the loop of modifying with Sakura Editor, transferring with WinSCP, and executing Python from Tera Term.

A simple one with low functionality is good.

I want to avoid things that are no longer needed once I get used to Python.

Countermeasure plan

It seems that Python will also work with Visual Studio. It seems that you can also do your favorite "step execution".

Examination of countermeasures

I couldn't consider multiple plans because I don't have much knowledge of Python, but I want to move it because "step execution" is hard to throw away on the subject of strengthening debugging. In order to run it on Visual Studio, it cannot be run on Win10 because it cannot be compiled (it is unknown whether the expression is appropriate).

** I can't compile because I don't have a library. If you don't have it, you have to make it. ** **

Library creation plan

Win10 does not have GPIO, so if you make a temporary GPIO library, can you execute it without a compile error? We will respond with the strategy. RPI. I use GPIO, but I am not particular about it. For now, it's just the most familiar choice.

environment

Windows10 64bit home VisualStudio 2019 Community Python C# Python 3.7 .NET 4.7.2 psycopg2 2.8.6 Npgsql v4.1.5 PostgreSQL PostgreSQL 13.0 64-bit A5:SQL Mk-2 2.15.1

What to make this time

GPIO library RPI. Make GPIO with a dummy. Create a Windows Forms program in C # for operation. RPI. PostgreSQL is used for communication between GPIO and C #. This is because it is troublesome to use interprocess communication, and the DB is more useful for this usage in terms of logs. You can play with it as you like in SQL. Python is psicopg2 and C # is Npgskl to connect to the DB.

** Simulate I / O using SQL with GPIO library and C #. ** **

Creating a PostgreSQL DB

キャプチャ001.PNG

I created a DB called pizero and created two tables. inputtable is for input, from C # to GPIO library. outputtable is for output, from GPIO library to C #.

create database pizero;

create table outputTable(
id serial
,hiduke timestamp
,pin integer
,data integer
,memo varchar(20)
);

create table inputTable(
id serial
,hiduke timestamp
,pin integer
,data integer
,memo varchar(20)
);

Creating a Python project

キャプチャ002.PNG Select Python. If you can't find it, you need to install it. キャプチャ003.PNG キャプチャ004.PNG It's done. キャプチャ005.PNG Open Python Package Management. キャプチャ006.PNG Enter psycopg2. The one with the up arrow seems to be an update, so I think it should be updated. キャプチャ007.PNG It has been various. At the beginning, click Run the following command. キャプチャ008.PNG Click Promote Now. キャプチャ009.PNG It's done. キャプチャ010.PNG It has been added to the list. キャプチャ011.PNG Make a Python sauce. There is an error in import.

piTes1.py



import time
import RPi.GPIO as GPIO

PIN_IN = 2
PIN_OUT =3
PIN_OUT2 =4

GPIO.setwarnings(False)

print('start')

GPIO.setmode( GPIO.BCM )
GPIO.setup( PIN_IN, GPIO.IN )
GPIO.setup( PIN_OUT, GPIO.OUT )
GPIO.setup( PIN_OUT2, GPIO.OUT )

for i in range(3):
    inData = GPIO.input( PIN_IN )

    if( inData == GPIO.LOW ):
        print('PIN_OUT')
        GPIO.output( PIN_OUT, GPIO.HIGH )
        GPIO.output( PIN_OUT2, GPIO.LOW )
    else:
        print('PIN_OUT2')
        GPIO.output( PIN_OUT, GPIO.LOW )
        GPIO.output( PIN_OUT2, GPIO.HIGH )

GPIO.cleanup()

print('end')

キャプチャ012.PNG Add a new item. キャプチャ013.PNG Make a Python package. The name is important. キャプチャ014.PNG It's done. キャプチャ015.PNG Also add a new item. I will add it in the package I made earlier. I want to put it in a package. キャプチャ016.PNG Create an empty Python file. The name is important. キャプチャ017.PNG It has been added to the list. キャプチャ018.PNG Create the source of GPIO library. The connection information to the DB needs to be adjusted to the environment. Server: localhost Port: 5432 Database: pizero User: postgres Password: postgres

GPIO.py



import time
import psycopg2

BCM = 1

IN = 1
OUT = 2

LOW = 0
HIGH = 1

outCount = 0
inCount = 0

connection = psycopg2.connect("host=localhost port=5432 dbname=pizero user=postgres password=postgres")
connection.autocommit = True

def setwarnings(flg):
	return 0

def setmode(mode):
	global outCount
	global inCount

	cur = connection.cursor()
	cur.execute("select coalesce(max(id),0) from outputtable")
	row = cur.fetchone()

	outCount = row[0]

	cur.execute("select coalesce(max(id),0) from inputtable")
	row = cur.fetchone()

	inCount = row[0]

	cur.close()

	return 0

def setup(pin,type):
	return 0

def cleanup():
	connection.close()
	return 0

def input(pin):
	global inCount

	ret = 0
	rowcount = 0

	while rowcount == 0:

		strSQL = "select * from inputtable where id > " + str(inCount)
		cur = connection.cursor()
		cur.execute(strSQL)
		row = cur.fetchone()

		rowcount = cur.rowcount

		if rowcount == 0:
			print('wait')
			time.sleep(5.0)

		if rowcount > 0:
			print(row)
			inCount = row[0]
			ret = row[3]

		cur.close()

	return ret

def output(pin,data):
	global outCount

	strSQL = "insert into outputtable(hiduke, pin, data, memo) values (now(), " + str(pin) + ", " + str(data) + ", 'output')"
	cur = connection.cursor()
	cur.execute(strSQL)
	cur.close()

	outCount += 1

	return 0

It just defines the functions used by the GPIO library. SQL processing for communication is included in the input function and output function. input function Wait endlessly for inserts from C #. Data larger than the known id is regarded as new data. I'll wait, but I'll get only one. output function Insert to inform C #. I'll just let you know, so don't wait.

キャプチャ019.PNG There is no error in import. I'm happy.

C # project creation

キャプチャ020.PNG Make it with Windows Forms. キャプチャ021.PNG キャプチャ022.PNG It's done. NuGet. キャプチャ023.PNG Select the reference and search for Npgskl. キャプチャ024.PNG Install it. キャプチャ025.PNG It has been added to the reference settings. キャプチャ026.PNG Make a form. キャプチャ027.PNG The C # source has been compiled.

Form1.cs



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using Npgsql;

namespace piTes1CS
{
    public partial class Form1 : Form
    {
        string connString = "Server=localhost;Port=5432;User Id=postgres;Password=postgres;Database=pizero";
        NpgsqlConnection conn;

        int inCount = 0;
        int outCount = 0;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            inCount = 0;
            outCount = 0;

            conn = new NpgsqlConnection(connString);
            conn.Open();

            var strSQL = "select coalesce(max(id),0) maxid from inputtable";
            var command = new NpgsqlCommand(strSQL, conn);

            var dataReader = command.ExecuteReader();
            if (dataReader.HasRows)
            {
                dataReader.Read();
                inCount = (int)dataReader["maxid"];
            }
            dataReader.Close();

            strSQL = "select coalesce(max(id),0) maxid from outputtable";
            command = new NpgsqlCommand(strSQL, conn);

            dataReader = command.ExecuteReader();
            if (dataReader.HasRows)
            {
                dataReader.Read();
                outCount = (int)dataReader["maxid"];
            }
            dataReader.Close();
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            conn.Close();
        }

        private void btnRead_Click(object sender, EventArgs e)
        {
            this.txtGPIO3.BackColor = Color.White;
            this.txtGPIO4.BackColor = Color.White;

            var strSQL = "select * from outputtable where id > " + outCount;
            var command = new NpgsqlCommand(strSQL, conn);

            var dataReader = command.ExecuteReader();
            if (dataReader.HasRows)
            {
                dataReader.Read();
                outCount = (int)dataReader["id"];
                int pin = (int)dataReader["pin"];
                int data = (int)dataReader["data"];
                string memo = (string)dataReader["memo"];

                Console.WriteLine("outCount=" + outCount + " inCount=" + inCount);

                if (pin == 3)
                {
                    this.txtGPIO3.Text = data.ToString();
                    this.txtGPIO3.BackColor = Color.Yellow;
                }
                if (pin == 4)
                {
                    this.txtGPIO4.Text = data.ToString();
                    this.txtGPIO4.BackColor = Color.Yellow;
                }
            }
            else
            {
                Console.WriteLine("wait");
            }
            dataReader.Close();
        }

        private void btnGPIO2_Click(object sender, EventArgs e)
        {
            if (this.txtGPIO2.TextLength > 0)
            {
                var strSQL = "insert into inputtable(hiduke, pin, data, memo) values (now(), 2, " + this.txtGPIO2.Text + ", 'btnWriteGPIO2')";

                var command = new NpgsqlCommand(strSQL, conn);
                command.ExecuteNonQuery();

                inCount++;
            }
        }
    }
}

C # does the opposite of Python. Insert the data for the input function of the GPIO library with the submit button. Get one data for output function of GPIO library with the receive button. The value is displayed on GPIO3 or GPIO4 with the receive button.

Try to move

キャプチャ028.PNG To clean the table, use Truncate. It also initializes the id value.


truncate table inputtable RESTART IDENTITY;
truncate table outputtable RESTART IDENTITY;

キャプチャ029.PNG Launch two Visual Studios and run Python and C # respectively. キャプチャ030.PNG I started Python. キャプチャ031.PNG I started C #. キャプチャ032.PNG Since Python is waiting for the input function, GPIO2 is assigned to GPIO. I just set HIGH and pressed the send button. It seems that Python is working fine. キャプチャ033.PNG After Python has executed the output function twice, press the receive button. GPIO3 is GPIO. It is displayed as LOW. キャプチャ034.PNG Press the receive button again. GPIO4 is GPIO. It was displayed as HIGH. It seems to be working fine. キャプチャ035.PNG キャプチャ036.PNG It is the state of the DB after it is finished.

Try to move

** By creating a dummy of GPIO library, you can debug on Win10 instead of on RaspberryPi. ** ** Considering the function on the C # side this time, I feel that it is enough to execute it while modifying SQL. ** It's not a simulator, it's a test code, so you have to make something that matches the movement of Python **, but if you still find it easy, it's probably worth a try. It is a sensor system, and if you get the log on the actual machine and put it in the table, you may be able to try the same movement as the actual machine. You can step through and check the values of variables that are running. Even CORE i5 10 years ago is not an enemy of the zero series, it is comfortable.

I tried L Chika in the zero series just because of the IoT atmosphere. Next is. .. ..

Currently, there are two strong enemies on the breadboard. It's a gyro sensor module and a motor driver IC, but what will happen? Even though there are fewer parts than the unstable multivibrator L Chika.

The more I read a software book, the more I can do, but why is that system (electronic circuit) useless (unhelpful)?

** For handicraft level electronic work challengers, the GPIO connector is the Away. ** **

I have to focus on the strong opponents on the breadboard of Away, so I don't have much power to avoid Python. Because it is a level that can not explain the operation of the unstable multivibrator.

Recommended Posts

Try debugging Python on Raspberry Pi with Visual Studio.
Working with GPS on Raspberry Pi 3 Python
Connect to MySQL with Python on Raspberry Pi
Try tweeting arXiv's RSS feed on twitter from Raspberry Pi with python
Remote debugging with Visual Studio 2017
Ubuntu 20.04 on raspberry pi 4 with OpenCV and use with python
Use vl53l0x with Raspberry Pi (python)
Try using ArUco on Raspberry Pi
Try L Chika with raspberry pi
Try moving 3 servos with Raspberry Pi
Build Python3 for Windows 10 on ARM with Visual Studio 2019 (x86) on Windows 10 on ARM
Control the motor with a motor driver using python on Raspberry Pi 3!
Detect "brightness" using python on Raspberry Pi 3!
Adafruit Python BluefruitLE works on Raspberry Pi.
Try to create a python environment with Visual Studio Code & WSL
Try fishing for smelt with Raspberry Pi
Programming normally with Node-RED programming on Raspberry Pi 3
Try Object detection with Raspberry Pi 4 + Coral
Run servomotor on Raspberry Pi 3 using python
Working with sensors on Mathematica on Raspberry Pi
Detect temperature using python on Raspberry Pi 3!
Run Python in C ++ on Visual Studio 2017
Use Jupyter Notebook with Visual Studio Code on Windows 10 + Python + Poetry + pyenv-win
Detect analog signals with A / D converter using python on Raspberry Pi 3!
Use python on Raspberry Pi 3 to light the LED with switch control!
Detect slide switches using python on Raspberry Pi 3!
Build Python development environment with Visual Studio Code
Try using a QR code on a Raspberry Pi
Run Python YOLOv3 in C ++ on Visual Studio 2017
I tried L-Chika with Raspberry Pi 4 (Python edition)
Detect magnet switches using python on Raspberry Pi 3!
Enjoy electronic work with GPIO on Raspberry Pi
Django with Python Tools 2.2 for Visual Studio (PTVS 2.2)
Power on / off your PC with raspberry pi
Try working with Mongo in Python on Mac
Get CPU information of Raspberry Pi with Python
Make DHT11 available on Raspberry Pi + python (memo)
Sound the buzzer using python on Raspberry Pi 3!
Play with your Ubuntu desktop on your Raspberry Pi 4
Build a Python development environment on Raspberry Pi
GPS tracking with Raspberry Pi 4B + BU-353S4 (Python)
Measure CPU temperature of Raspberry Pi with Python
Try scraping with Python.
GPGPU with Raspberry Pi
pigpio on Raspberry pi
DigitalSignage with Raspberry Pi
Cython on Raspberry Pi
Try to use up the Raspberry Pi 2's 4-core CPU with Parallel Python
Record temperature and humidity with systemd on Raspberry Pi
Run LEDmatrix interactively with Raspberry Pi 3B + on Slackbot
Try to visualize the room with Raspberry Pi, part 1
Try using the temperature sensor (LM75B) on the Raspberry Pi.
Control brushless motors with GPIOs on Raspberry Pi Zero
Python development environment with Windows + Anaconda3 + Visual Studio Code
Python development environment with Windows + Python + PipEnv + Visual Studio Code
Japanese output when dealing with python in visual studio
Install pyenv on Raspberry Pi and version control Python
Output to "7-segment LED" using python on Raspberry Pi 3!
Troubleshoot with installing OpenCV on Raspberry Pi and capturing
Display USB camera video with Python OpenCV with Raspberry Pi
Let's operate GPIO of Raspberry Pi with Python CGI