static void Main(string[] args) { var options = ParseOptions(args); if (options == null) { return; } IServiceCollection serviceCollection = new ServiceCollection(); serviceCollection.AddLogging(); var sp = serviceCollection.BuildServiceProvider(); sp.GetRequiredService <LoggerFactory>().AddConsole().AddDebug(); log = sp.GetRequiredService <ILogger <Program> >(); log.LogInformation("-=Pca9685 Sample=-"); log.LogInformation("Running {0}", System.Runtime.InteropServices.RuntimeInformation.OSDescription); log.LogInformation("Options:" + Environment.NewLine + options); var pulse = CalculatePulse(options.PwmFrequency, 50); log.LogInformation("Pulse={0}", pulse); if (!System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Linux)) { log.LogWarning("Windows detected. Exiting"); return; } log.LogInformation("Connecting..."); try { using (var driver = new I2cDriver(options.SdaPin.ToProcessor(), options.SclPin.ToProcessor())) { log.LogInformation("Creating device..."); var device = new Pca9685Connection(sp, driver.Connect(options.DeviceAddress)); log.LogInformation("Setting frequency..."); device.SetPwmUpdateRate(options.PwmFrequency); while (!Console.KeyAvailable) { log.LogInformation("Set channel={0} to {1}", options.Channel, options.PwmOn); device.SetPwm(options.Channel, 0, options.PwmOn); Thread.Sleep(1000); log.LogInformation("Set channel={0} to {1}", options.Channel, options.PwmOff); device.SetPwm(options.Channel, 0, options.PwmOff); Thread.Sleep(1000); } log.LogInformation("Key pressed. Exiting."); } } catch (InvalidOperationException e) { log.LogError(new EventId(0), e, "Failed to connect? Do you have a Pca9685 IC attached to the i2c line and powered on?"); } }
private void Run(string[] args) { using (var driver = new I2cDriver(ProcessorPin.Pin2, ProcessorPin.Pin3)) { // which pwm channel; allow override from args[0] as 0..n int c = 0; if (args.Length > 0) { Int32.TryParse(args[0], out c); } PwmChannel channel = (PwmChannel)c; Console.WriteLine($"Using PCA9685 channel {channel.ToString()}"); // allow override of min/max cycle if (args.Length > 1) { Int32.TryParse(args[1], out _servoMin); } if (args.Length > 2) { Int32.TryParse(args[2], out _servoMax); } int i2cAddress = 0x40; Console.WriteLine($"Using i2C address 0x{i2cAddress:x}"); // device support and prep channel var device = new Pca9685Connection(driver.Connect(i2cAddress)); device.SetPwm(channel, 0, 0); int freq = 60; Console.WriteLine($"Setting PWM frequency to {freq}"); var pwmFrequency = Frequency.FromHertz(freq); device.SetPwmUpdateRate(pwmFrequency); Console.WriteLine("* * * When entering values, prefix the input with \"!\" to specify a raw pulse value rather than a degree value (e.g. !680). * * *"); Console.WriteLine("\nPress any key to exit...\n"); // loop until ENTER string input; do { Console.Write("Enter rotation 0 to 180 or RETURN to exit? "); input = Console.ReadLine().Trim(); int cycle; if (TryParse(input, out cycle)) { Console.WriteLine($"Setting PWM channel {channel.ToString()} to {cycle}"); device.SetPwm(channel, 0, cycle); } } while (input != string.Empty); } }
/// <summary> /// Initializes a new instance of the <see cref="Motor_Hat"/> class. /// </summary> /// <param name="addr">I2C address default is 0x60</param> /// <param name="freq">Frequency</param> public Motor_Hat(I2cDriver driver, int addr = 0x60, int freq = 1600) { for (int i = 0; i < 4; i++) { motors.Add(new DC_Motor(this, i)); // Creates 4 DC Motors and adds them to the list } steppers.Add(new Stepper_Motor(this, 1)); // Creates Stepper Motor 1 steppers.Add(new Stepper_Motor(this, 2)); // Creates Stepper Motor 2 connection = driver.Connect(addr); _pwm = new Pca9685Connection(connection); // Connects to the Motor Hat _pwm.SetPwmUpdateRate(freq); // Sets the frequency }
static void Main(string[] args) { var options = ParseOptions(args); if (options == null) { return; } log.Info("-=Pca9685 Sample=-"); log.Info(m => m("Running {0}", Environment.OSVersion)); log.Info("Options:" + Environment.NewLine + options); var pulse = CalculatePulse(options.PwmFrequency, 50); log.Info(m => m("Pulse={0}", pulse)); if (Environment.OSVersion.Platform != PlatformID.Unix) { log.Warn("Windows detected. Exiting"); return; } log.Info("Connecting..."); try { using (var driver = new I2cDriver(options.SdaPin.ToProcessor(), options.SclPin.ToProcessor())) { log.Info("Creating device..."); var device = new Pca9685Connection(driver.Connect(options.DeviceAddress)); log.Info("Setting frequency..."); device.SetPwmUpdateRate(options.PwmFrequency); while (!Console.KeyAvailable) { log.Info(m => m("Set channel={0} to {1}", options.Channel, options.PwmOn)); device.SetPwm(options.Channel, 0, options.PwmOn); Thread.Sleep(1000); log.Info(m => m("Set channel={0} to {1}", options.Channel, options.PwmOff)); device.SetPwm(options.Channel, 0, options.PwmOff); Thread.Sleep(1000); } log.Info("Key pressed. Exiting."); } } catch (InvalidOperationException e) { log.Error("Failed to connect? Do you have a Pca9685 IC attached to the i2c line and powered on?", e); } }
private void Run(string[] args) { Console.WriteLine("Press any key to exit..."); using (var driver = new I2cDriver(ProcessorPin.Pin2, ProcessorPin.Pin3)) { // random object to add some spice to the output Random rnd = new Random(); // device support int i2cAddress = 0x40; var device = new Pca9685Connection(driver.Connect(i2cAddress)); var pwmFrequency = Frequency.FromHertz(60); device.SetPwmUpdateRate(pwmFrequency); // task support CancellationTokenSource cancelSource = new CancellationTokenSource(); List <Task> tasks = new List <Task>(); // create the channel(s) and start task(s) PwmChannel[] pwmChannels = { PwmChannel.C0, }; // add more channels for more additional LEDs foreach (var channel in pwmChannels.Distinct()) { // pass random sleep ms to have LEDs at different fade speeds Task task = Task.Run(() => RunLed(device, channel, rnd.Next(20, 41), cancelSource.Token)); } // loop until key pressed while (!Console.KeyAvailable) { Thread.Sleep(250); } // cancel task(s) and wait cancelSource.Cancel(); Task.WaitAll(tasks.ToArray()); } }
private IPwmDevice GetRealDevice() { PwmFrequency = new Frequency(60); DeviceAddress = 0x40; try { _i2cDriver = new I2cDriver(SdaPin.ToProcessor(), SclPin.ToProcessor()); } catch (Exception e) { Log.Error("Failed to initialise i2c driver. Did you forget sudo?", e); } Log.Info("Creating device..."); var device = new Pca9685Connection(_i2cDriver.Connect(DeviceAddress)); Log.Info("Setting frequency..."); device.SetPwmUpdateRate(PwmFrequency); // # Set frequency to 60 Hz IsConnected = true; return(device); }
public void Action(ActionBase baseAction, CancellationToken cancelToken, dynamic config) { ServoSimpleAction action = (ServoSimpleAction)baseAction; SetState("validateSetup"); ValidateSetup(config, action); ProcessorPin sda = config.i2cSdaBcmPin; ProcessorPin scl = config.i2cSclBcmPin; using (var driver = new I2cDriver(sda, scl)) { SetState("setup"); PwmChannel[] channels = Newtonsoft.Json.JsonConvert.DeserializeObject <PwmChannel[]>(config.i2cChannel.ToString()); int i2cAddress = config.i2cAddress; int pwmFrequency = config.pwmFrequency; Frequency frequency = Frequency.FromHertz(pwmFrequency); // device support and prep channel SetState("connection"); var pcaConnection = new Pca9685Connection(driver.Connect(i2cAddress)); pcaConnection.SetPwmUpdateRate(frequency); // pre delay SetState("preDelay"); if (cancelToken.WaitHandle.WaitOne(action.PreDelayMs)) { return; // looks like we're cancelling } // handle each rotation // // Note: there could be more configured channels (i.e. servos) in the configuration; the user doesn't // have to use them all; we map the user's n array elements to first n configured channels in // the server plugin config List <Task> servoTasks = new List <Task>(); for (int i = 0; i < action.RotationDegrees.Length; ++i) { // if we're skipping this servo, loop to next if (action.RotationDegrees.Length == 0) { continue; } SetState($"startRotate_{i}"); RotateServoConfiguration options = new RotateServoConfiguration { PcaConnection = pcaConnection, PwmChannel = channels[i], PwmMaximumPulse = _pwmMaxPulse[i], PwmMinimumPulse = _pwmMinPulse[i], RotationDegree = action.RotationDegrees[i], RotationDelayMs = action.RotationDelayMs[i], }; Task task = Task.Run(() => RotateServo(options, cancelToken)); servoTasks.Add(task); } // wait for all servos to complete; don't set state since tasks will be doing that // as the servos rotate Task.WaitAll(servoTasks.ToArray()); // post delay SetState("postDelay"); if (cancelToken.WaitHandle.WaitOne(action.PostDelayMs)) { return; // looks like we're cancelling } } }