Author Topic: programming 101  (Read 12136 times)

0 Members and 1 Guest are viewing this topic.

Online IanB

  • Super Contributor
  • ***
  • Posts: 12609
  • Country: us
Re: programming 101
« Reply #25 on: November 18, 2014, 10:57:42 pm »
... on Windows, you get all that char vs. tchar vs. wchar vs. whatever, for one of many such examples.  The first time I created a console project in VS, I was stuck for days trying to figure out how I'm supposed to deal with characters, since obviously Windows had it's own way of doing things that did not look like the examples in your typical book.  Having never really learned Windows programming, I'm still not sure of the right way to do many simple things because of architectural differences from the basic, portable coding practices that have been the staple of tutorials since C was created.

It's really not so complicated. The Windows extensions are just that--extensions--not differences.

If you write standard C in Visual Studio the compiler will compile and run standard C. It is a standards conforming compiler.

See the attached screenshot, for example.
 

Offline hamster_nz

  • Super Contributor
  • ***
  • Posts: 2828
  • Country: nz
Re: programming 101
« Reply #26 on: November 18, 2014, 11:57:41 pm »
It's really not so complicated. The Windows extensions are just that--extensions--not differences.

If I was interested in Electronics and programming, with minimal existing skills in either, my preference would be: Arduino, then Linux on Small ARM board (e.g. Pi), then PC Linux and finally Windows.

Solid example - creating a burglar alarm alarm for a reed switch on a door, and make a noise when it is open.  Code to support it

1. Arduino - nice and simple - and fully understandable.
Code: [Select]
   setup()
   {
      PinMode(1,INPUT);   -- to switch in door;
      PinMode(2, OUTPUT); -- to beeper
   }
   loop()
  {
     if(DigitalRead(1) = 0)
     {
        // Waggle the beeper
         DigitalWrite(2,1);
         delay(1);
         DigitalWrite(2,0);
         delay(1);
     }
     else
         delay(1);
   }

2. On small Linux box, after a bit of cut-and-paste from various pages. Quite a bit of black magic
Code: [Select]
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

#define MODE_FILE_FORMAT "/sys/devices/virtual/misc/gpio/mode/gpio%d"
#define PIN_FILE_FORMAT  "/sys/devices/virtual/misc/gpio/pin/gpio%d"

int main(int c, char *v[])
{
  char buffer[128];
  FILE *modefile, *pinfile;
  int pin;

  if(c != 2) {
    fprintf(stderr,"usage: %s [pin]\n",v[0]);
    exit(2);
  }
  pin = 1;

  /* Open the GPIO control files */
  sprintf(buffer,MODE_FILE_FORMAT,pin);
  modefile = fopen(buffer,"w");
  if(modefile == NULL)
  {
    fprintf(stderr,"Unable to open mode file: %s\n",buffer);
    exit(2);
  }

  sprintf(buffer,PIN_FILE_FORMAT,pin);
  pinfile = fopen(buffer,"r");
  if(pinfile == NULL)
  {
    fprintf(stderr,"Unable to open pin file: %s\n",buffer);
    exit(2);
  }

  /* Set the pin to be an input pin */
  fwrite("0",1,1,modefile);

  /* Read and display the value of the GPIO pin */
  while(1)
  {
    char buffer[4];
    fseek(pinfile, 0, SEEK_SET);
    if(fread(buffer,1,4,pinfile) <= 0) {
      fprintf(stderr,"Error on read\n");
      break;
    }
    if(buffer[0] = '0')
       system("aplay alarm.wav");
    usleep(100000);
  }

  fclose(modefile);
  fclose(pinfile);
  return 0;
}

3. On PC Linux box, just like 2, but with no Hardware GPIO pins to play with, so find something like http://numato.com/32-channel-usb-gpio-module and adapt the code to it. A bit more black magic and very few hits in Google for howtos.

4. On Windows
   First, work out what you are trying to do (which is hard when you don't know what you are doing)
   Then find and buy a  GPIO board - which will cost more than an Arduino.
   Then read a lot on how to access the GPIO pins (usually involves importing DLLs and other tricks) and custom setting in the build environment
   Then work out how to play sounds through the Win32 API multimedia interface
   Then work out how to use timers to check the pin at regular intervals.
   Then finally start writing code - something as newbie-incomprehensible as this, but would include calls to "PlaySound(TEXT("recycle.wav"), NULL, SND_FILENAME);" and some thing to do the timer.

Then write code like this, where the actual code that does real work ("SetPinLevel(133, 0);") looks pretty much the same as the Arduino code:

Code: [Select]
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;   ///< To use Toradex C Win32 DLLs
 
namespace GPIO_LED
{
    public partial class Form1 : Form
    {
        [DllImport("GPIOLib.dll", CharSet = CharSet.Auto)]  ///< Importing DLL
        public static extern bool SetPinAltFn(Int32 pinNum, Int32 altFn, bool dirOut); ///< External function declaration
 
        [DllImport("GPIOLib.dll", CharSet = CharSet.Auto)]
        public static extern void InitGPIOLib();
 
        [DllImport("GPIOLib.dll", CharSet = CharSet.Auto)]
        public static extern bool SetPinLevel(Int32 gpioNum, Int32 val);
 
        [DllImport("GPIOLib.dll", CharSet = CharSet.Auto)]
        public static extern void DeInitGPIOLib();
 
        public Form1()                       
        {
            InitializeComponent();       
            SetPinAltFn(133, -1, true); ///< To set the SODIMM_133 as GPIO output
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            SetPinLevel(133, 1);        ///< Sets SODIMM_133 as high when button1 is pressed
        }
 
        private void button2_Click(object sender, EventArgs e)
        {
            SetPinLevel(133, 0);        ///< Sets SODIMM_133 as low when button2 is pressed 
        }
 
        private void FormClose(object sender, EventArgs e)
        {
            DeInitGPIOLib();            ///< Deinitializes GPIO library and frees up system resources upon closing the program
        }       
    }
}

Which takes me back to my original advice - if you want to play around with programming and electronics then don't use your PC - buy and Arduino starter kit.
Gaze not into the abyss, lest you become recognized as an abyss domain expert, and they expect you keep gazing into the damn thing.
 

Offline zapta

  • Super Contributor
  • ***
  • Posts: 6366
  • Country: 00
Re: programming 101
« Reply #27 on: November 19, 2014, 12:11:42 am »
If you get the Arduino Uno, get also this excellent book. 

http://exploringarduino.com/

http://amzn.com/1118549368
« Last Edit: November 19, 2014, 12:13:34 am by zapta »
 

Online IanB

  • Super Contributor
  • ***
  • Posts: 12609
  • Country: us
Re: programming 101
« Reply #28 on: November 19, 2014, 12:58:27 am »
Solid example - creating a burglar alarm alarm for a reed switch on a door, and make a noise when it is open.  Code to support it

Let me fix this for you:

Quote
1. Arduino
   First, work out what you are trying to do (which is hard when you don't know what you are doing)
...

2. On small Linux box,
   First, work out what you are trying to do (which is hard when you don't know what you are doing)
...

3. On PC Linux box,
   First, work out what you are trying to do (which is hard when you don't know what you are doing)
...

4. On Windows
   First, work out what you are trying to do (which is hard when you don't know what you are doing)
...

If you are an absolute beginner, then you can't avoid figuring out where to begin, on any platform.

Also, I don't understand why you have used simple C style programming on Linux, but have passed that by on Windows and gone for something very complicated and obfuscated instead? Especially when my prior post showed that free Windows tools support standard C console programming perfectly well.

Quote
Which takes me back to my original advice - if you want to play around with programming and electronics then don't use your PC - buy and Arduino starter kit.
Your point may be perfectly valid, but that's not news since I pointed to the Arduino in Reply #1 right at the top.

On the PC, you can learn to program. To program, note. Not necessarily learn to interface to external hardware. That's a different dimension.
 

Offline SirNick

  • Frequent Contributor
  • **
  • Posts: 589
Re: programming 101
« Reply #29 on: November 19, 2014, 01:14:55 am »
It's really not so complicated. The Windows extensions are just that--extensions--not differences.

If you write standard C in Visual Studio the compiler will compile and run standard C. It is a standards conforming compiler.

OK, but taking the char stuff for example, what are the limitations of using char[]?  Most of the tutorials I see have the T() macro and all kinds of other crazy stuff going on, plus all these API calls ending in _A and _W.  I assume things aren't much different provided you stick to ASCII <127, but I have no idea what happens to international characters in filenames or text strings.

Advice I've read online varies from "don't bother -- just use char[]" to "always use t_char, stay away from w_char" to "never use t_char, only use w_char" to "depends on whether you've defined UNICODE".  Then, there are the file I/O functions.  I'm sure open() and read() -- or fopen() and fread() -- do exist, but there are a whole slew of C API functions native to Windows that appear to be preferable, given the examples online.

I'm sure I'm making it worse than it needs to be, but I'm ignorant of why there are so many ways to do the same thing, and therefore, what those things do differently to warrant their existence.

In Linux, you just use plain old C.  If large character sets are necessary, it's probably in UTF8 and can mostly be ignored unless you're mangling text yourself.
 

Online IanB

  • Super Contributor
  • ***
  • Posts: 12609
  • Country: us
Re: programming 101
« Reply #30 on: November 19, 2014, 01:24:57 am »
In Linux, you just use plain old C.  If large character sets are necessary, it's probably in UTF8 and can mostly be ignored unless you're mangling text yourself.

In Windows also, unless you have a specific reason to do otherwise, just use plain old C.

There are no limitations of char[] that you need care about. The char data type stores 8 bit bytes and will handle ASCII text. If you are a native English speaker, and have no special need for extended character sets or Unicode, then you can pretend Unicode doesn't exist. (Unless you happen to open a file that was saved by another program with multi-byte character encoding, but that will mess with you on Unix just as much.)

If you want or need to interact with the Windows APIs for graphical programming, then you may need to start caring. But I write nearly all my experimental C and C++ programs as simple text console programs that use standard input and standard output. I just use the standard language features and everything is hunky dory.
 

Offline miguelvp

  • Super Contributor
  • ***
  • Posts: 5550
  • Country: us
Re: programming 101
« Reply #31 on: November 19, 2014, 01:41:43 am »
char can handle EFIGS languages if you use what people call the ANSI char set, so you are good for English, French, Italian, German & Spanish. But that's no longer the case and UTF8 is wasteful for some languages while wide chars with UTF16 is not (although it would be wastefull for just EFIGS implementations).

tchar allows you to have code that will support wide characters without changing anything other than defining UNICODE. Would that be complicated to a beginner? maybe, but then again if that's how it is done then a beginner will learn it that way 8 bit chars are fading to a thing of the past.

As for Arduino for a beginner, I don't buy that it's hard to figure out what you want to do, we all started from the beginning and we managed just fine, the Arduino IDE enables rookies to get a lot of things done without a lot of complications, just like when someone discovered how powerful a peek and a poke where back in basic and we didn't have any trouble figuring how the interrupts worked and i/o etc.

The ramp up time to get things done in an Arduino is orders of magnitude lower (as in faster) than other platforms, I will dare to say that it's easier than basic back in the days where you had to learn about the bios and what addresses did what and call those from your assembly code because memory restrictions and there was code in the bios that will do what you wanted to do. Now we have libraries and a ton of them so there is more flexibility and we have better documentation.

As far as windows, if you think it's complicated give the windows 8 api a try. Even for experienced windows programmers it's a big leap but at least it's more asynchronous processing friendly and complicated just translates to job security :) Even as much as people moan about COM it's better than CORBA and even if I hate that marshalling is going on behind the scenes, it allows  your code to scale on multi core/multi processors and it's able to give you more concurrency on your code.

Also there are so many samples out there for anything that learning any of them is really not an issue, but just do something instead of thinking that it's hard to do.

Edit: objects are rest, just want to keep on resting, once they are in movement, they just want to keep on moving :)
« Last Edit: November 19, 2014, 01:46:06 am by miguelvp »
 

Offline zapta

  • Super Contributor
  • ***
  • Posts: 6366
  • Country: 00
Re: programming 101
« Reply #32 on: November 19, 2014, 01:58:22 am »
The small problems with Arduino:
1) The programming language is in essence C - the Arduino language is merely a set of C/C++ functions that can be called from your code. Your sketch undergoes minor changes (e.g. automatic generation of function prototypes) and then is passed directly to a C/C++ compiler (avr-gcc+). In general it is not as efficient as the code made in avr gcc+/WinAvr alone.

That's incorrect, Arduino gives you full avr GCC c/c++ and you can write your code as efficient or low level as you want.
 

Offline hamster_nz

  • Super Contributor
  • ***
  • Posts: 2828
  • Country: nz
Re: programming 101
« Reply #33 on: November 19, 2014, 01:58:43 am »
Also, I don't understand why you have used simple C style programming on Linux, but have passed that by on Windows and gone for something very complicated and obfuscated instead? Especially when my prior post showed that free Windows tools support standard C console programming perfectly well.
Google for "wIndows GPIO programming in C" and see what you get - I get answers for the BeagleBone Black before I get any usable Windows Code!

 Maybe I should have instead used WindowsCE code (that I guess won't run on a PC) - it has at least a dozen lines that look like ANSI C, most of them the ones with just a brace on it:
Code: [Select]
#include <Windows.h>
#include <GPIO_API.h>
 
int WINAPI WinMain(     HINSTANCE hInstance,
   HINSTANCE hPrevInstance,
   LPTSTR    lpCmdLine,
   int       nCmdShow)
{
  HANDLE hGPIO_API;     
  DWORD count;
 
  RETAILMSG( 1, (TEXT("Testing GPIO\n")));
 
  hGPIO_API = InitGPIOAPI();
 
  if( hGPIO_API != INVALID_HANDLE_VALUE )
  {
    SetOutputGPIOPin( hGPIO_API, 30 );
 
    for( count = 0; count < 20; count++ )
    {
        SetGPIOPin( hGPIO_API, 30 );
        RETAILMSG( 1, (TEXT( "set GPIO 30 is %s\r\n"), ReadGPIOPin(hGPIO_API, 30)?TEXT("Set"):TEXT("Clear")));
        Sleep( 1000 );
 
        ClearGPIOPin( hGPIO_API, 30 );
        RETAILMSG( 1, (TEXT( "clear GPIO 30 is %s\r\n"), ReadGPIOPin(hGPIO_API, 30)?TEXT("Set"):TEXT("Clear")));
        Sleep( 1000 );
    }
    DeinitGPIOAPI( hGPIO_API );
  }
  RETAILMSG(1,(TEXT("Done\n")));
 
  return 0;
}


Rant mode on. Having done *a lot* of C programming on Windows, going back to using WinSock() under Windows 3.0, I find systems programming C on Windows is an abhorrence. Well, maybe that is a little strong, but it sucks big-time.

Have you ever tried to write a true Windows service? ever tried to receive and send data to/from a Serial Port while also doing other stuff? writing network services that need to service multiple sessions? Process multiple file streams at once? accessing physical disks devices to query their size? ever used shared memory and other IPC?  And then accessing GPIO, DACs  or ADCs where no standard API exists? It is a bit like the Chewbacca Defence - "To learn to use C on a platform where the underlying system APIs are not compatible with the native C paradigm - it does not make sense! you must acquit!"

Yep, I'll agree that the random nature of IOCTLs are a bit dodgy on UNIX, but at least the UNIX paradigm is somewhat consistent - almost everything ends up being a file handle to a character or block device, and you can read or write to it.

If I have to program C for pleasure, give me UNIX any day. If you are paying me to program, well that is somewhat different...
« Last Edit: November 19, 2014, 02:03:06 am by hamster_nz »
Gaze not into the abyss, lest you become recognized as an abyss domain expert, and they expect you keep gazing into the damn thing.
 

Offline kjn4685Topic starter

  • Regular Contributor
  • *
  • Posts: 154
  • Country: us
Re: programming 101
« Reply #34 on: November 19, 2014, 05:30:16 am »
Is there software to wright code and then simulate the code that I have written with out a broad.
 

Offline dannyf

  • Super Contributor
  • ***
  • Posts: 8221
  • Country: 00
Re: programming 101
« Reply #35 on: November 19, 2014, 11:38:14 am »
Yes and no, depending on what code you have written.
================================
https://dannyelectronics.wordpress.com/
 

Offline kjn4685Topic starter

  • Regular Contributor
  • *
  • Posts: 154
  • Country: us
Re: programming 101
« Reply #36 on: November 20, 2014, 11:14:12 pm »
Like c
 

Offline hamster_nz

  • Super Contributor
  • ***
  • Posts: 2828
  • Country: nz
Re: programming 101
« Reply #37 on: November 21, 2014, 01:14:05 am »
AVRstudio has a simulator in it...
Gaze not into the abyss, lest you become recognized as an abyss domain expert, and they expect you keep gazing into the damn thing.
 

Offline dannyf

  • Super Contributor
  • ***
  • Posts: 8221
  • Country: 00
Re: programming 101
« Reply #38 on: November 21, 2014, 11:46:42 am »
Quote
Like c

You may or may not debug like C, depending on the code you have written.
================================
https://dannyelectronics.wordpress.com/
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf