I have been reading the documentation
I can get gpioServo to run
My motor spins
my goal is to spin my motor one revolution per second
which means; as far as i understand it; a frequency of 1 hz and a duty cycle of 100%
but i can only get gpio servo to work
here is my current code
//#include <QDebug>
//#include <QApplication>
#include <pigpio.h>
#include <iostream>
#include <chrono>
int main(int argc, char *argv[]) {
// QApplication a(argc, argv);
gpioInitialise();
//
//
// system("clear");
// std::cout << std::endl << "Running..." << std::endl;
//
// gpioServo(13, 2000);
// std::cout << std::endl << "Calibrate hi..." << std::endl;
// time_sleep(3);
//
//
// gpioServo(13, 1000);
// std::cout << std::endl << "Calibrate low..." << std::endl;
// time_sleep(3);
//
// gpioServo(13, 0);
// std::cout << std::endl << "Calibrate stop..." << std::endl;
std::cout << std::endl << gpioHardwarePWM(13, 10000, 100000) << std::endl;
std::cout << std::endl << "Run duty cycle..." << std::endl;
time_sleep(3);
system("clear");
std::cout << std::endl << "Done" << std::endl;
gpioTerminate();
// qDebug() << "Hello World";
// return QApplication::exec();
return 0;
}
To me I was assuming the duty cycle would be 100 and the frequency would be 1
but the numbers in my function parameters 10000 and 100000 come from a post on one of the forums i read by the author of pigpio
either way nothing has worked yet with gpioPWM for me
I am in the learning stage so this is very basic but gpioHardwarePWM returns a 0 and the documention on pigpio says that means its good but no spinning motor
I'm just trying learn please a help me see what I'm missing?
Documentation: https://abyz.me.uk/rpi/pigpio/
Related
I am trying to get joystick input using glfw. I am using nintendo pro controller.
The code seems pretty simple and straightfoward, but I can't seem to get accurate joystick data.
I used
int axesCount;
const float *axes = glfwGetJoystickAxes(GLFW_JOYSTICK_1, &axesCount);
and tried to access joystick data by
axes[0], axes[1], axes[2], and axis[3]
glfwGetJoystickAxes gave me an accurate number for axesCount, which is 4.
But even if I moved the joystick the axes array always returned 1.52590219e-05.
Below is the whole code for my appliation
#include "pch.h"
#include <iostream>
#include <gl/glew.h>
#include <GLFW/glfw3.h>
int main()
{
GLFWwindow *window;
// initialize
if (!glfwInit()) {
return -1;
}
// create window and its opengl context
window = glfwCreateWindow(640, 480, "OpenGL Project Tutorial", NULL, NULL);
if (!window) {
glfwTerminate();
return -1;
}
// make the window's context current
// loop untill the user closes the window
while (!glfwWindowShouldClose(window)) {
glClear(GL_COLOR_BUFFER_BIT);
// render OpenGL here
int present = glfwJoystickPresent(GLFW_JOYSTICK_1);
std::cout << "Joystick/Gamepad status: " << present << std::endl;
int axesCount;
const float *axes = glfwGetJoystickAxes(GLFW_JOYSTICK_1, &axesCount);
if (1 == present) {
//std::cout << "Number of axes available: " << axesCount << std::endl;
std::cout << "Axis 1: " << axes[0] << std::endl;
std::cout << "Axis 2: " << axes[1] << std::endl;
std::cout << "Axis 3: " << axes[2] << std::endl;
std::cout << "Axis 4: " << axes[3] << std::endl;
std::cout << std::endl;
std::cout << std::endl;
std::cout << std::endl;
}
// swap front and back buffers
glfwSwapBuffers(window);
// poll for and process events
glfwPollEvents();
}
glfwTerminate();
return 0;
}
It didn't matter whether I put
int axesCount;
const float *axes = glfwGetJoystickAxes(GLFW_JOYSTICK_1, &axesCount);
inside the while loop or not.
Any help would be appreciated, thanks.
I am trying to test sending data from 2 distinct network adapters on the same machine to a common remote endpoint, but I keep getting "bind: invalid argument" AFTER the first bind comes through. What am I missing? I have searched, tried to modify the code, but I was not able to find any lead and I keep getting the same error. The same happens when I swap out the IPs.
#include <iostream>
#include <boost/asio.hpp>
#include <sstream>
#include <thread>
#include <chrono>
#include <boost/random.hpp>
const unsigned int MS_INTERVAL = 100;
enum CMD_ARG
{
PROG_NAME = 0,
LOCAL_IP_1,
LOCAL_IP_2,
REMOTE_IP,
REMOTE_PORT
};
using namespace boost::asio;
using std::string;
using std::cout;
using std::endl;
int main(int argc, char *argv[]) {
if(argc == 5)
{
//Test data initialisation
unsigned int counter = 0;
boost::random::mt19937 randSeed; // seed, produces randomness out of thin air
boost::random::uniform_int_distribution<> randGen(-1000,1000); // Random number generator between -100 and 100
//Initialise ASIO service
io_service io_service;
//socket creation and binding (one per network adapter)
std::cout << "Opening and binding local sockets to " << argv[LOCAL_IP_1] << " and " << argv[LOCAL_IP_2] << std::endl;
ip::tcp::socket socket1(io_service);
ip::tcp::socket socket2(io_service);
socket1.open(ip::tcp::v4());
socket2.open(ip::tcp::v4());
socket1.bind(ip::tcp::endpoint(ip::address::from_string(argv[LOCAL_IP_1]), 0));
std::cout << "1/2 done" << std::endl;
socket2.bind(ip::tcp::endpoint(ip::address::from_string(argv[LOCAL_IP_2]), 0));
//Connection to remote end point starting with defining the remote endpoint
std::istringstream iss(argv[REMOTE_PORT]);
unsigned int port = 0;
iss >> port;
ip::tcp::endpoint remoteEndpoint = ip::tcp::endpoint( ip::address::from_string(argv[REMOTE_IP]), port);
std::cout << "Connecting to " << argv[REMOTE_IP] << " on port " << port << std::endl;
socket1.connect(remoteEndpoint);
std::cout << "1/2 done" << std::endl;
socket2.connect(remoteEndpoint);
std::cout << "Ready" << std::endl;
while(1)
{
//Build message
std::ostringstream oss;
oss << counter << "," << randGen(randSeed) << "," << randGen(randSeed) << "," << randGen(randSeed) << std::endl;
//Send message on both interfaces
boost::system::error_code error1, error2;
write(socket1, boost::asio::buffer(oss.str()), error1);
write(socket2, boost::asio::buffer(oss.str()), error2);
//Check errors
if( !error1 && !error2) {
cout << "Sending: " << oss.str() << endl;
counter++;
}
else {
cout << "Error: " << (error1?error1.message():error2.message()) << endl;
}
std::this_thread::sleep_for(std::chrono::milliseconds(MS_INTERVAL));
}
}
else
{
std::cout << "Usage: <program> <local IP 1> <local IP 2> <remote server IP> <server's opened port>" << argc << std::endl;
}
return 0;
}
socket1.bind(ip::tcp::endpoint(ip::address::from_string(argv[LOCAL_IP_1]), 0));
...
socket1.bind(ip::tcp::endpoint(ip::address::from_string(argv[LOCAL_IP_2]), 0));
You are trying to bind the same socket1 twice. Likely you mean socket2 in the second statement.
Given the following code:
#include <SDL2/SDL.h>
#include <SDL2/SDL_audio.h>
#include <iostream>
#include <chrono>
#include <thread>
static void SDLCallback(void *userData, Uint8 *data, int bytes) {
std::cerr << "SDLCallback: " << bytes / sizeof(float) << "\n";
}
int main() {
using namespace std::literals;
SDL_Init(SDL_INIT_AUDIO);
SDL_AudioDeviceID m_deviceId{};
SDL_AudioSpec m_desired, m_obtained;
m_desired.freq = 48000;
m_desired.format = AUDIO_F32SYS;
m_desired.channels = 2;
m_desired.samples = 1024;
m_desired.callback = SDLCallback;
m_desired.userdata = nullptr;
m_deviceId = SDL_OpenAudioDevice(nullptr, 0, &m_desired, &m_obtained, 0);
std::cerr << "SDL device: " << m_deviceId << std::endl;
if (m_deviceId < 2) {
std::cerr << "SDL: Couldn't open audio: " << SDL_GetError() << std::endl;
exit(1);
}
std::cerr << "rate: " << m_obtained.freq << "\n";
std::cerr << "samples: " << m_obtained.samples << "\n";
std::cerr << "bytes: " << m_obtained.size << "\n";
std::cerr << "channels: " << (int)m_obtained.channels << "\n";
SDL_PauseAudioDevice(m_deviceId, 0);
for (int i = 0; i < 10; i++) {
std::this_thread::sleep_for(100ms);
std::cerr << (SDL_GetAudioDeviceStatus(m_deviceId) == SDL_AUDIO_PLAYING)
<< std::endl;
}
SDL_CloseAudioDevice(m_deviceId);
SDL_Quit();
}
I am seeing the following output:
$ ./a.out
SDL device: 2
rate: 48000
samples: 1024
bytes: 8192
channels:
SDLCallback: 2048
SDLCallback: 2048
1
1
1
1
1
1
1
1
1
1
<program gets stuck on SDL_CloseAudioDevice>
That is, the SDLCallback function is called only twice at the beginning then not anymore, yet the audio is still marked as running. I am using PulseAudio.
What can I do to prevent that ? Where is my program wrong ? It works if I kill PulseAudio, but PulseAudio works fine for all my other software.
And if it is not wrong, how can I make sure that my users will never encounter that issue ? How can I recover without getting the program stuck on SDL_CloseAudioDevice ? As PulseAudio is very common among Linux users.
I did two months search on the web for a proper file locking mechanism to be used in a C++ program.
I found a lot on "C and fnctl" which I could proof to work. But all really proper working locking mechanism, that I could proof to work in Linux are only based on file descriptors.
As this seems to be something really old fashined and in actual C++17 style of writing C++ code with file- and ip-streams not using that mechanism, I only came up with something that works with using what was presented here:
Not able to ofstream using __gnu_cxx::stdio_filebuf
My Question is, is this really the only mechanism working? To connect both worlds?
I looked in all these books to find anything about fcntl and C++, but was not successful:
[Der C++ Programmierer Cxx20]
(https://www.hanser-elibrary.com/doi/book/10.3139/9783446465510)
[The C++ Programming Language] (https://www.stroustrup.com/C++.html)
[C++ Das Umfassende Handbuch]
(https://www.rheinwerk-verlag.de/c-plusplus-das-umfassende-handbuch/)
[Modern C++ Programming Cookbook Second Edition]
(https://www.packtpub.com/product/modern-c-programming-cookbook-second-edition/9781800208988)
My question to the C++ gurus here is, if I missed something, or if the following code is, today, begin of 2021 the best we could do.
Short explanation of what the code is a proof for:
We have a C++ Code which adds usernames and its LSF-processes to a conf-file, which is read by SSH-server to allow user access to that machine. As at the same time two or more running processes of this code could lead to concurrent attempts of adding or deleting users from this file could occur, we have to proof that proper file locking is preventing that. Without using an extra "access" file, which also could be a solution.
This is some example code I tested:
#include <iostream>
#include <string>
#include <thread>
#include <chrono>
#include <fcntl.h>
#include <unistd.h>
#include <ext/stdio_filebuf.h>
using namespace std::this_thread; // for sleep_for
int main( ) {
// set unbuffered concole output
std::cout.setf(std::ios::unitbuf);
const char* filename {"testfile.txt"};
// get input from input_from_user
std::string input_from_user_string;
std::cout << "Please give input to change in the file: ";
std::cin >> input_from_user_string;
int add_1_del_2 = 0;
std::cout << "Please give 1 if you want to add to the file or 2 if you want to delete from file: ";
std::cin >> add_1_del_2;
int input_from_user_time;
std::cout << "Please give seconds to wait: ";
std::cin >> input_from_user_time;
// opening file
std::cout << "Opening File" << std::endl;
mode_t mode = S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH; //664
int fd;
fd = open(filename, O_RDWR | O_CREAT, mode);
// printing out information about file descriptor
std::cout << " Dexc:" << fd << std::endl;
// generating C++-streams on filedescriptor
__gnu_cxx::stdio_filebuf<char> sourcebufin(fd, std::ios::in);
__gnu_cxx::stdio_filebuf<char> sourcebufout(fd, std::ios::out);
std::istream myfilein(&sourcebufin);
std::ostream myfileout(&sourcebufout);
// -----------
// check for file Locking or exit
// -----------
// creating structure for file locking
struct flock fl;
fl.l_type = F_RDLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 0;
// set file locking for read
fl.l_type = F_RDLCK;
std::cout << "Checking for Lock on file" << std::endl;
// check for file locking on file for read only once
(void) fcntl(fd, F_GETLK, &fl);
if (fl.l_type != F_UNLCK) {
std::cout << "File is locked for reading by process "
<< fl.l_pid
<< ", in status"
<< ((fl.l_type == F_WRLCK) ? 'W' : 'R')
<< ", start="
<< fl.l_start
<< ", end="
<< fl.l_len
<< std::endl;
}
else {
(void) printf("File is unlocked for reading\n");
}
// set file locking for write
fl.l_type = F_WRLCK;
// check for file locking on file for write in a loop
for (int i = 1; i < 11; i++) {
//printf("Checking for lock %d of 10 times...\n", i);
std::cout << "Checking for lock "
<< i
<< " of 10 times..."
<< std::endl;
(void) fcntl(fd, F_GETLK, &fl);
if (fl.l_type != F_UNLCK) {
//(void) printf("File is locked by process %d, in status %c, start=%8ld, end=%8ld\n", fl.l_pid,
// , fl.l_start, fl.l_len);
std::cout << "File is locked by process "
<< fl.l_pid
<< ", in status"
<< ((fl.l_type == F_WRLCK) ? 'W' : 'R')
<< ", start="
<< fl.l_start
<< ", end="
<< fl.l_len
<< std::endl;
sleep(10);
}
else {
(void) printf("File is unlocked\n");
break;
}
}
// -----------
// apply lock for write on file
// -----------
// locking file
std::cout << "Locking file for write" << std::endl;
// set file locking for write again, as checking on lock resets it
fl.l_type = F_WRLCK;
if (fcntl(fd, F_SETLKW, &fl) == -1) {
perror("fcntl");
abort();
}
// -----------
// wait some time
// -----------
std::cout << "Now waiting for " << input_from_user_time << " seconds, keeping the file locked..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(input_from_user_time));
// -----------
// read from file
// -----------
std::cout << "Reading from file... " << std::endl;
myfilein.seekg(0, std::ios::end);
size_t size_before = myfilein.tellg();
myfilein.seekg(0);
std::string filecontent{""};
filecontent.reserve(size_before);
std::cout << "Length of file is: " << size_before << std::endl;
// read full content of file in string "filecontent"
filecontent.assign((std::istreambuf_iterator<char>(myfilein)),
std::istreambuf_iterator<char>());
// -----------
// print output about read data
// -----------
std::cout << "Length of filecontent-string: " << filecontent.size() << std::endl;
std::cout << "Content of File begin" << std::endl;
std::cout << "----------" << std::endl;
std::cout << filecontent << std::endl;
std::cout << "----------" << std::endl;
// -----------
// Apply changes on read in data depending on given input
// -----------
if (add_1_del_2 == 2) {
std::cout << "Runmode: Del" << std::endl;
std::string string_to_delete = input_from_user_string+"\n";
std::string::size_type pos_of_found_substring = filecontent.find(string_to_delete);
if (pos_of_found_substring != std::string::npos) {
filecontent.erase(pos_of_found_substring, string_to_delete.length());
}
else {
}
}
if (add_1_del_2 == 1) {
std::cout << "Runmode: Append" << std::endl;
filecontent.append(input_from_user_string);
}
std::cout << "Content of String after change" << std::endl;
std::cout << "----------" << std::endl;
std::cout << filecontent << std::endl;
std::cout << "----------" << std::endl;
// -----------
// write out to file, truncate before to length of new string
// -----------
std::cout << "Now starting the write out..." << std::endl;
myfilein.seekg(0);
ftruncate(fd,filecontent.length());
myfileout.seekp(0);
myfileout << filecontent;
myfileout.flush();
myfileout.clear();
// -----------
// read from file for a second time and printout content
// -----------
std::cout << "Reading from file again... " << std::endl;
myfilein.seekg(0, std::ios::end);
size_t size_after = myfilein.tellg();
myfilein.seekg(0);
std::string filecontent_after{""};
filecontent_after.reserve(size_after);
std::cout << "Length of file is now: " << size_after << std::endl;
// read full content of file in string "filecontent"
filecontent_after.assign((std::istreambuf_iterator<char>(myfilein)),
std::istreambuf_iterator<char>());
std::cout << "Length of filecontent_after-string: " << filecontent_after.size() << std::endl;
std::cout << "Content of File end" << std::endl;
std::cout << "----------" << std::endl;
std::cout << filecontent_after << std::endl;
std::cout << "----------" << std::endl;
// -----------
// unlocking file and close file
// -----------
printf("Unlocking...\n");
fl.l_type = F_UNLCK;
if (fcntl(fd, F_SETLK, &fl) == -1) {
perror("fcntl");
abort();
}
close(fd);
// -----------
// done
// -----------
std::cout << "done" << std::endl;
exit(0);
}
I ask for your comments on this or perhaps how to improve.
Alexander Bruns
In my application I am using a Gtk::DrawingArea like this:
Window win;
DrawingArea area;
Box box(ORIENTATION_VERTICAL);
area.signal_realize().connect(sigc::ptr_fun(&on_video_area_realize));
box.pack_start(myWidgets, true, true);
box.pack_start(area, false, false);
win.add(box);
win.show_all();
The problem is, the function on_video_area_realize is not being called and if I query the status of the DrawingArea with area.get_realized(), it is false, so it has not been realized yet.
I do not understand why it has not been realized? As far as I understand, a widget is realized when it is added to a window - which, as far as I think, I am doing already.
The realize signal happens when the window (and its children) is showed. The following code (I tested this with Gtkmm 3.24.20):
#include <iostream>
#include <gtkmm.h>
void on_video_area_realize()
{
std::cout << "Video drawing area realized!" << std::endl;
}
int main(int argc, char *argv[])
{
std::cout << "Gtkmm version : " << gtk_get_major_version() << "."
<< gtk_get_minor_version() << "."
<< gtk_get_micro_version() << std::endl;
auto app = Gtk::Application::create(argc, argv, "org.gtkmm.examples.base");
Gtk::Window window;
Gtk::Box layout{Gtk::ORIENTATION_VERTICAL};
Gtk::Label label{"Example"};
std::cout << "Checkpoint 1" << std::endl;
Gtk::DrawingArea area;
std::cout << "Checkpoint 2" << std::endl;
area.signal_realize().connect(sigc::ptr_fun(&on_video_area_realize));
std::cout << "Checkpoint 3" << std::endl;
layout.pack_start(label, true, true);
layout.pack_start(area, false, false);
std::cout << "Checkpoint 4" << std::endl;
window.add(layout);
window.show_all();
std::cout << "Checkpoint 5" << std::endl;
return app->run(window);
}
Yields the following output:
Gtkmm version : 3.24.20
Checkpoint 1
Checkpoint 2
Checkpoint 3
Checkpoint 4
Video drawing area realized!
Checkpoint 5
From this, we can see that the drawing area is realized, but not when added to the window.